通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:
// 调用 MyPlugin.install(Vue)
Vue.use(MyPlugin)
new Vue({
// …组件选项
})
Vue.use 会自动阻止多次注册相同插件,届时即使多次调用也只会注册一次该插件。
插件暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象,然后在install中去注册各个组件。
官方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)
//将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
}
}