plugin(Function | Object)
Function
或者是Object
<br/>若是是個對象,必須提供install方法javascript
若是是一個函數,會被直接看成install
函數執行vue
install
函數接受參數,默認第一個參數爲Vue,其後參數爲註冊組件時傳入的arguments
java
組件.js export const testObj = { install(Vue, arg) { } } export const testFn = founction(Vue, arg) { } index.js import { testObj, testFn } from './組建.js' Vue.use(testObj, arg) Vue.use(testFn, arg)
建議組件採用第一種寫法,根據use源碼,當採用第二種寫法時,this指針指向null數組
if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args) } else if (typeof plugin === 'function') { plugin.apply(null, args) }
官方use源碼app
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 Vue對象 return this } //調用`toArray`方法 const args = toArray(arguments, 1) args.unshift(this) //將Vue對象拼接到數組頭部 if (typeof plugin.install === 'function') { //若是組件是對象,且提供install方法,調用install方法將參數數組傳入,改變`this`指針爲該組件 plugin.install.apply(plugin, args) } else if (typeof plugin === 'function') { //若是傳入組件是函數,這直接調用,可是此時的`this`指針只想爲`null` plugin.apply(null, args) } //在保存註冊組件的數組中添加 installedPlugins.push(plugin) return this } }
toArray
方法源碼函數
export function toArray (list: any, start?: number): Array<any> { start = start || 0 let i = list.length - start //將存放參數的數組轉爲數組,併除去第一個參數(該組件) const ret: Array<any> = new Array(i) //循環拿出數組 while (i--) { ret[i] = list[i + start] } return ret }