Vue.use源码解析

 1 import { toArray } from '../util/index'
 2 
 3 export function initUse (Vue: GlobalAPI) {
 4   Vue.use = function (plugin: Function | Object) {
 5     const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
 6     if (installedPlugins.indexOf(plugin) > -1) {
 7       return this
 8     }
 9 
10     // additional parameters
11     const args = toArray(arguments, 1)
12     args.unshift(this)
13     if (typeof plugin.install === 'function') {
14       plugin.install.apply(plugin, args)
15     } else if (typeof plugin === 'function') {
16       plugin.apply(null, args)
17     }
18     installedPlugins.push(plugin)
19     return this
20   }
21 }

首先判断传入的参数plugin的属性是否已被注册,如果存在且逻辑值为真,那么直接返回,后边的代码就不会在执行。

我们先假设plugin未被注册,那么继续往下执行

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
}

当执行toArray(arguments,1),会生成一个新数组ret,长度 = arguments.length-1,然后进行while循环,依次倒序把arguments的元素赋值给ret,因为ret比arguments长度少1,所以最终等同于arguments把除了第一个元素外的其余元素赋值给ret。toArray主要作用就是把类数组转化为真正的数组,这样才能调用数组的方法。因为此处我只引入一个plugin参数,即arguments=[plugin],所以toArray返回为空数组[]。

接着往下执行,args.unshift(this),等同于[].unshift(Vue),即args = [Vue];

1 if (typeof plugin.install === 'function') {
2       plugin.install.apply(plugin, args)
3     } else if (typeof plugin === 'function') {
4       plugin.apply(null, args)
5     }
6     installedPlugins.push(plugin)

此处判断plugin的install是否为函数,如果为函数,立即执行pluign.install方法,install方法传入的参数为args内数组元素,即install接受的第一个参数为Vue.

如果plugin的install不是函数,那么判断plugin本身是否为函数,如果为函数,那么执行plugin函数,且参数为args内数组元素。

综上所述,Vue.use的作用其实就是执行一个plugin函数或者执行pluign的install方法进行插件注册,并且向plugin或其install方法传入Vue对象作为第一个参数,use的其他参数作为plugin或install的其他参数。

posted on 2019-03-11 09:52  时光游弋  阅读(275)  评论(0编辑  收藏  举报