Vue.use源码

官方对 Vue.use() 方法的说明:

通过全局方法 Vue.use() 使用插件;
Vue.use 会自动阻止多次注册相同插件;
它需要在你调用 new Vue() 启动应用之前完成;
Vue.use() 方法至少传入一个参数,该参数类型必须是 Object 或 Function,如果是 Object 那么这个 Object 需要定义一个 install 方法,如果是 Function 那么这个函数就被当做 install 方法。在 Vue.use() 执行时 install 会默认执行,当 install 执行时第一个参数就是 Vue,其他参数是 Vue.use() 执行时传入的其他参数。

源码:
// Vue源码文件路径:src/core/global-api/use.js

import { toArray } from '../util/index'

export function initUse (Vue: GlobalAPI) {
  Vue.use = function (plugin: Function | Object) {  // use接收的参数限制是函数或对象两种类型
    const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
    if (installedPlugins.indexOf(plugin) > -1) {  // 判断插件是否被注册过
      return this
    }

    const args = toArray(arguments, 1) // 将传入的参数(除plugin)外整理成数组
    args.unshift(this) // 将Vue作为数组的第一项
    if (typeof plugin.install === 'function') { // plugin为对象,并且属性install为函数
      plugin.install.apply(plugin, args)
    } else if (typeof plugin === 'function') { // plugin为函数
      plugin.apply(null, args)
    }
    installedPlugins.push(plugin) // 标记已注册
    return this
  }
}

// Vue源码文件路径:src/core/shared/util.js

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作用:

在 install 里可以拿到 Vue, 可以在 install 里处理逻辑,如:进行全局注册组件等。
component.js

import a from './a'
import b from './b'
let components = { a, b }
const installBase = {
   install (Vue) {
      Object.keys(components).map(key => Vue.component(key, components[key]))
   }
}

main.js

import Vue from 'vue'
import component from './component.js'
Vue.use(component)

new Vue({
 ...
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容