vue開發中的幾個高級應用


vue.use

我們使用的第三方 vue.js 插件。如果插件是一個對象,必須提供install方法。如果插件是一個函數,它會被作為install方法。install方法調用時,會將Vue作為參數傳入。該方法需要在調用new Vue()之前被調用。

我們在使用插件或者第三方組件庫的時候用到Vue.use這個方法,比如

import iView from 'iview' Vue.use(iView)

那么Vue.use到底做了些什么事情呢?我們先來看一下源碼

import { toArray } from '../util/index' export function initUse(Vue: GlobalAPI) { Vue.use = function(plugin: Function | Object) { const installedPlugins = this._installedPlugins || (this._installedPlugins = []) if (installedPlugins.indexOf(plugin) > -1) { return this } // additional parameters const args = toArray(arguments, 1) args.unshift(this) if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else if (typeof plugin === 'function') { plugin.apply(null, args) } installedPlugins.push(plugin) return this } }

我們由以上可以看出,plugin參數為函數或者對象類型,首先Vue會去尋找這個插件在已安裝的插件列表里有沒有,如果沒有,則進行安裝插件,如果有則跳出函數,這保證插件只被安裝一次。

接着通過toArray方法將參數變成數組,再判斷plugin的install屬性是否為函數,或者plugin本身就是函數,最后執行plugin.install或者plugin的方法。

舉個例子

下面我們來舉個實際例子
1、編寫兩個插件

const Plugin1 = { install(a) { console.log(a) } } function Plugin2(b) { console.log(b) } export { Plugin1, Plugin2 }

2、引入並 use 這兩個插件

import Vue from 'vue' import { Plugin1, Plugin2 } from './plugins' Vue.use(Plugin1, '參數1') Vue.use(Plugin2, '參數2')

此時我們運行項目代碼就可以用到上面兩個插件了。

 

Vue.mixin

混入 (mixin) 提供了一種非常靈活的方式,來分發 Vue 組件中的可復用功能。一個混入對象可以包含任意組件選項。當組件使用混入對象時,所有混入對象的選項將被“混合”進入該組件本身的選項。

1、定義一個 mixin.js

export default mixin { data() { return { name: 'mixin' } }, created() { console.log('mixin...', this.name); }, mounted() {}, methods: { //日期轉換 formatDate (dateTime, fmt = 'YYYY年MM月DD日 HH:mm:ss') { if (!dateTime) { return '' } moment.locale('zh-CN') dateTime = moment(dateTime).format(fmt) return dateTime } } }

2、在vue文件中使用mixin

import '@/mixin'; // 引入mixin文件 export default { mixins: [mixin], //用法 data() { return { userName: "adimin", time: this.formatDate(new Date()) //這個vue文件的數據源data里面的time就是引用混入進來的方法 } } } 

或者在全局中使用在main.js中,所有頁面都能使用了

import mixin from './mixin' Vue.mixin(mixin) 

合並選項

當組件和混入對象含有同名選項時,這些選項將以恰當的方式進行“合並”。

  • data對象在內部會進行遞歸合並,並在發生沖突時以組件數據優先。
  • 同名鈎子函數將合並為一個數組,因此都將被調用。混入對象的鈎子將在組件自身鈎子之前調用。
  • 值為對象的選項,例如 methods、components 和 directives,將被合並為同一個對象。兩個對象鍵名沖突時,取組件對象的鍵值對。

 

Vue.extend

Vue.extend 屬於 Vue 的全局 API。它使用基礎 Vue 構造器,創建一個“子類”。參數是一個包含組件選項的對象。如下:

<div id="app"></div> var Profile = Vue.extend({ template: '<p>{{firstName}} {{lastName}}</p>', data: function () { return { firstName: 'Walter', lastName: 'White' } } }) // 創建 Profile 實例,並掛載到一個元素上。 new Profile().$mount('#app')

應用實例

我們常用 Vue.extend 封裝一些全局插件,比如 toast, diolog 等。

下面以封裝一個 toast 組件為例。

1、編寫組件

  • 根據傳入的 type 確定彈窗的類型(成功提示,失敗提示,警告,加載,純文字)
  • 設置彈窗消失的時間
<template> <div> <transition name="fade"> <div class="little-tip" v-show="showTip"> <img src="/success.png" alt="" width="36" v-if="type=='success'" /> <img src="/fail.png" alt="" width="36" v-if="type=='fail'" /> <img src="/warning.png" alt="" width="36" v-if="type=='warning'" /> <img src="/loading.png" alt="" width="36" v-if="type=='loading'" class="loading" /> <span>{{msg}}</span> </div> </transition> </div> </template> <script> export default { data() { return { showTip: true, msg: '', type: '' } }, mounted() { setTimeout(() => { this.showTip = false }, 1500) } } </script> <style lang="less" scoped> /* 樣式略 */ </style>

2、利用 Vue.extend 構造器把 toast 組件掛載到 vue 實例下

import Vue from 'vue' import Main from './toast.vue' let Toast = Vue.extend(Main) let instance const toast = function(options) { options = options || {} instance = new Toast({ data: options }) instance.vm = instance.$mount() document.body.appendChild(instance.vm.$el) return instance.vm } export default toast

3、在 main.js 引入 toast 組價並掛載在 vue 原型上

import Vue from 'vue' import toast from './components/toast' Vue.prototype.$toast = toast

4、在項目中調用

this.$toast({ msg: '手機號碼不能為空' }) this.$toast({ msg: '成功提示', type: 'success' })

Vue.extend 和 Vue.component 的區別

  • component是需要先進行組件注冊后,然后在 template 中使用注冊的標簽名來實現組件的使用。Vue.extend 則是編程式的寫法。
  • 控制component的顯示與否,需要在父組件中傳入一個狀態來控制或者在組件外部用 v-if/v-show 來實現控制,而 Vue.extend 的顯示與否是手動的去做組件的掛載和銷毀。

資源搜索網站大全https://55wd.com 廣州品牌設計公司http://www.maiqicn.com

Vue.directive

注冊或獲取全局指令。指令定義函數提供了幾個鈎子函數(可選):

  • bind: 只調用一次,指令第一次綁定到元素時調用,可以定義一個在綁定時執行一次的初始化動作。
  • inserted: 被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
  • update: 被綁定元素所在的模板更新時調用,而不論綁定值是否變化。通過比較更新前后的綁定值。
  • componentUpdated: 被綁定元素所在模板完成一次更新周期時調用。
  • unbind: 只調用一次, 指令與元素解綁時調用。

應用實例

下面封裝一個復制粘貼文本的例子。

1、編寫指令 copy.js

const vCopy = { bind (el, { value }) { el.$value = value // 用一個全局屬性來存傳進來的值 el.handler = () => { if (!el.$value) { alert('無復制內容') return } // 動態創建 textarea 標簽 const textarea = document.createElement('textarea') // 將該 textarea 設為 readonly 防止 iOS 下自動喚起鍵盤,同時將 textarea 移出可視區域 textarea.readOnly = 'readonly' textarea.style.position = 'absolute' textarea.style.left = '-9999px' // 將要 copy 的值賦給 textarea 標簽的 value 屬性 textarea.value = el.$value // 將 textarea 插入到 body 中 document.body.appendChild(textarea) // 選中值並復制 textarea.select() // textarea.setSelectionRange(0, textarea.value.length); const result = document.execCommand('Copy') if (result) { alert('復制成功') } document.body.removeChild(textarea) } // 綁定點擊事件,就是所謂的一鍵 copy 啦 el.addEventListener('click', el.handler) }, // 當傳進來的值更新的時候觸發 componentUpdated (el, { value }) { el.$value = value }, // 指令與元素解綁的時候,移除事件綁定 unbind (el) { el.removeEventListener('click', el.handler) } } export default vCopy

2、注冊指令

import copy from './copy' // 自定義指令 const directives = { copy } // 這種寫法可以批量注冊指令 export default { install (Vue) { Object.keys(directives).forEach((key) => { Vue.directive(key, directives[key]) }) } }

3、在 main.js 引入並 use

 
import Vue from 'vue' import Directives from './JS/directives' Vue.use(Directives)

這樣就可以在項目直接用 vCopy 指令了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM