Vue.use源码解析

112 阅读2分钟

Vue.use(plugin)

  • 参数
    • {Object | Function} plugin
  • 用法
    1. 安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。
    2. install 方法调用时,会将 Vue 作为参数传入。该方法需要在调用 new Vue() 之前被调用。
    3. 当 install 方法被同一个插件多次调用,插件将只会被安装一次。
  • 插件

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

    1. 添加全局方法或者 property。如:vue-custom-element
    2. 添加全局资源:指令/过滤器/过渡等。如 vue-touch
    3. 通过全局混入来添加一些组件选项。如 vue-router
    4. 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。
    5. 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router
  • 如何开发插件
MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }
  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })
  // 3. 注入组件选项
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })
  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}

Vue.use源码解析

export function initUse (Vue: GlobalAPI) {
  //规定plugin的类型函数或者对象
  Vue.use = function (plugin: Function | Object) {
    //获取所有已经注册的插件
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    //已经安装过直接返回
    if (installedPlugins.indexOf(plugin) > -1) {
      return this
    }
    //从arguments获取参数,toArray第二个值为1是去除传入的第一参数,及Vue
    const args = toArray(arguments, 1)
    args.unshift(this)
    //对象,调用install方法
    if (typeof plugin.install === 'function') {
      plugin.install.apply(plugin, args)
    //方法,直接调用install
    } else if (typeof plugin === 'function') {
      plugin.apply(null, args)
    }
    //添加进已注册组件
    installedPlugins.push(plugin)
    return this
  }
}
//类数组,转为数组
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
}

总结

Vue.use能完成什么功能,取决于函数或者对象的Object如何编写的