Vue-use 源码分享

268 阅读1分钟

定义

Vue 注册组件的时候需要使用该方法。这一篇 wiki 探究一下该方法多工作原理。

源码

// main.js 调用方式 举例 Vue-router
Vue.use(Vue-router);


// Vue.use 源码
import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {

  // 这里的 plugin 就是 Vue.use 传进来的插件
  Vue.use = function (plugin: Function | Object) {

    // 初始化 _installedPlugins,用于存储已注册的插件
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))


    // 如果存在,直接 return ,防止重复注册
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }

    // 拿到除开第一个参数的所有参数,第一个参数是 plugin。
    const args = toArray(arguments, 1)

    // 将当前上下文(Vue)插入新的参数数组中
    args.unshift(this)

    /**
     * 2种注册方式:
     * 1.plugin 有 install 方法直接调用注册
     * 2.直接调用该 plugin
     */
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }

    // 已注册的插件推入数组中
    installedPlugins.push(plugin)
    return this
  }
}