需要使用vue.use()安裝的插件,要含有install
vue.use()可以對Vue添加全局功能
全局功能包括:
-
添加全局方法或者 property。如:vue-custom-element
-
添加全局資源:指令/過濾器/過渡等。如 vue-touch
-
通過全局混入來添加一些組件選項。如 vue-router
-
添加 Vue 實例方法,通過把它們添加到
Vue.prototype
上實現。 -
一個庫,提供自己的 API,同時提供上面提到的一個或多個功能。如 vue-router
use源碼:
/* @flow */ 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 } }
可以看出,use執行時走以下邏輯:
首先判斷this._installedPlugins這個數組變量中是否已包含參數plugin,若包含包含則不再執行下面的邏輯(此處實現插件多次use也只安裝一次的效果)
若不包含則取use方法的除第一位的其他參數(此處實現插件的傳參的效果,例如:Vue.use(plugin,參數))
取得其他參數后,在參數的第一位添加this(this就是Vue類的this,綁定在this上的全局功能,也就是綁定在Vue類的全局功能,new Vue實例時,這些全局功能也就存在於vue實例上了)
若use傳的參數plugin的install是一個function時執行install並傳入之前邏輯得到的參數數組
若use傳的參數plugin是function時執行plugin並傳入之前邏輯得到的參數數組
installedPlugins數組添加plugin,也就是this._installedPlugins的數組添加plugin
於是在插件編寫時添加全局變量的方法
MyPlugin.install = function (Vue, options) { // 1. 添加全局方法或 property Vue.myGlobalMethod = function () { // 邏輯... } // 2. 添加全局資源 Vue.directive('my-directive', { bind (el, binding, vnode, oldVnode) { // 邏輯... } ... }) // 3. 注入組件選項 Vue.mixin({ created: function () { // 邏輯... } ... }) // 4. 添加實例方法 Vue.prototype.$myMethod = function (methodOptions) { // 邏輯... } }