.1 use 概念
安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入,这样插件中就不在需要依赖 Vue 了。(扩展应用的功能)
1.2 插件的功能
- 添加全局指令、全局过滤器(Vue3 不再支持过滤器)、全局组件。
- 通过全局混入来添加一些组件选项。
- 添加实例方法,通过把它们添加到
Vue.prototype
/app.config.globalProperties
上实现。
1.3 实现原理
Vue.use = function (plugin: Function | Object) {
// 插件缓存
const installedPlugins = this._installedPlugins || (this._installedPlugins = [])
if (installedPlugins.indexOf(plugin) > -1) {
// 如果已经有插件 直接返回
return this
}
// additional parameters
const args = toArray(arguments, 1) // 除了第一项其他的参数整合成数组
args.unshift(this) // 将Vue 放入到数组中
if (typeof plugin.install === "function") {
// 调用install方法
plugin.install.apply(plugin, args)
} else if (typeof plugin === "function") {
// 直接调用方法
plugin.apply(null, args)
}
installedPlugins.push(plugin) // 缓存插件
return this
}
Vue3 中使用app.use进行插件的注册,原理同 Vue2~
const app = {
use(plugin: Plugin, ...options: any[]) {
if (installedPlugins.has(plugin)) {
__DEV__ && warn(`Plugin has already been applied to target app.`)
} else if (plugin && isFunction(plugin.install)) {
installedPlugins.add(plugin)
plugin.install(app, ...options)
} else if (isFunction(plugin)) {
installedPlugins.add(plugin)
plugin(app, ...options)
} else if (__DEV__) {
warn(`A plugin must either be a function or an object with an "install" ` + `function.`)
}
return app
},
}