Vue.use 如何注册插件
参考答案
Vue.use 做了什么
Vue.use = function (plugin) {
const installed = this._installedPlugins || (this._installedPlugins = [])
if (installed.indexOf(plugin) > -1) return this // 幂等去重
const args = toArray(arguments, 1)
args.unshift(this) // Vue 构造器放第一位
if (typeof plugin.install === 'function') plugin.install.apply(plugin, args)
else if (typeof plugin === 'function') plugin.apply(null, args)
installed.push(plugin)
return this // 支持链式
}
要点:
- 参数顺序 Vue 在最前,所以
install(Vue, options)能挂Vue.prototype.$xxx、Vue.component、Vue.directive、Vue.mixin; - 幂等:
_installedPlugins去重,重复 use 不重复安装; - 返回
this支持Vue.use(a).use(b); - Vue 3 对应
app.use(plugin, options),install(app, ...options),通过app.config.globalProperties、app.component、app.provide提供能力;内部用 Set 去重。
常见插件内容:全局组件、全局指令、原型方法($http)、全局 mixin、以及 router/pinia 自身。