Vue.use

我们通常会使用 Vue.use 来加载第三方模块,那么 Vue.use 具体做什么
源码很简单,也不多,简单看一下

// core/global-api/use.js
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
  }
}

从源码我们看到,Vue.use 首先检查_installedPlugins 是否有内容,没有的话创建空数组,判断 use 里的参数是否已经存在,存在了则不会再执行
在下面我们看到,将 pluginpush 到数组中,然后判断依赖是否存在 install,如果存在,直接执行依赖的 install,不存在的话,直接执行依赖,最后将依赖存到数组中,防止依赖多次执行

0