关于Vue.use()

在vue开发当中,Vue.use()用于引入组件。
下面是use.js的源码
···

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.js主要分为判断插件是否存在以及插件的引用两部。
首先,通过vue.use(plugin)接收到的组件plugin,并且类型必须是Function | Object

当插件不存在,继续执行,执行到

    const args = toArray(arguments, 1)
    args.unshift(this)

这两步主要做的是参数的处理。toArray()用于把类数组argument转化为数组,然后通过unshift()将数组右移,在数组首部添加this对象,也就是Vue对象。

下面是toArray源码

function toArray (list, start) {
  start = start || 0;
  var i = list.length - start;
  var ret = new Array(i);
  while (i--) {
    ret[i] = list[i + start];
  }
  return ret
}

toArray()接收两个参数arguments和1,生成一个新的数组ret,通过自减赋值ret[i] = list[i + start];。这里的ret其实就是arguments除了第一个元素以外的所有元素。
然后args.unshift(this)会把Vue对象放在args数组头部。

接下来执行的是

    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin)

关于这里的判断,上面说过,plugin的类型必须是Function | Object,而对象类型的plugin其实是带有install函数的,比如

const pluginObj = {
  install (...) {
    ...
  }
}

function pluginFun (...) {
  ...
}

也就是说,如果传入的是对象,那就调用插件的install方法并通过apply()方法将install方法改变this的指向为plugin。
args作为参数传递给install方法。
插件类型为function时,插件运行的上下文this指向null(严格模式下;非严格模式下指向window)

installedPlugins.push(plugin)在这之后将插件push到插件数组中,表示已注册。

了解了Vue.use后,对于插件的开发也会有帮助。

你可能感兴趣的:(关于Vue.use())