vue 源码分析之 use
用法
vue.use(plugin, arguments)
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
plugin.apply(null, args)
}官方 use 源码
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 Vue对象
return this
}
//调用 `toArray` 方法
const args = toArray(arguments, 1) // 把类似数组的对象转化成真正的数组
args.unshift(this) //向前添加 this 到 args
// install 的传递的参数有关系, 第一个参数是 vue 构造器, 第二个参数是一个可选的选项 options
//将Vue对象拼接到数组头部
if (typeof plugin.install === 'function') {
//如果组件是对象,且提供install方法,调用install方法将参数数组传入,改变 `this` 指针为该组件
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
//如果传入组件是函数,这直接调用,但是此时的 `this` 指针指向为 `null`
plugin.apply(null, args)
}
//在保存注册组件的数组中添加
installedPlugins.push(plugin)
return this
}
}为什么 Vue-Router Vuex ElementUI 的时候需要 vue.use(). 而引入 axios 的时候,不需要 Vue.use()
参考文献
最后更新于