精读 Vue 官方文档系列 🎉
定义插件
插件通常用来向 Vue 添加全局功能或资源:
- 添加全局方法或者 property。
- 添加
Vue实例方法(添加到Vue.prototype)。 - 添加全局的指令。
- 通过全局混入来添加一些组件选项。
- 注册
Vue组件。
示例:
export let _Vue;
MyPlugin.install = function (Vue, opt) {
if (install.installed && _Vue === Vue) return;
install.installed = true;
//添加全局属性或方法
app.globalProperties = {
appName: "myApp",
version: "0.1.1",
myGlobalMethod() {},
};
// 添加全局指令
Vue.directive("my-directive", {
bind(el, binding, vnode, oldVnode) {
// 逻辑...
},
});
//添加全局混入
Vue.mixin({
beforeCreate() {
if (isDef(this.$options.router)) {
this._routerRoot = this;
this._router = this.$options.router;
this._router.init(this);
Vue.util.defineReactive(this, "_route", this._router.history.current);
} else {
this._routerRoot = (this.$parent && this.$parent._routerRoot) || this;
}
},
destroyed() {
//....
},
});
//添加实例方法
Object.defineProperty(Vue.prototype, "$router", {
get() {
return this._routerRoot._router;
},
});
Object.defineProperty(Vue.prototype, "$route", {
get() {
return this._routerRoot._route;
},
});
//注册组件
Vue.component("RouterView", View);
Vue.component("RouterLink", Link);
};
Vue.js 的插件应该暴露一个 install 方法,这个方法的第一个参数是 Vue 构造器,在调用 Vue.use(MyPlugin) 进行注册的时候自动传入,第二个参数是一个可选的对象选项,为插件的注册提供一些初始化参数。
使用插件
通过全局方法 Vue.use() 来使用(注册)插件。它需要在你调用 new Vue() 启动应用之前完成:
// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
new Vue({
// ...组件选项
})
参数是一个可选的对象选项,用于帮助插件注册时进行一些初始化操作。
Vue.use(MyPlugin, { someOption: true })
Vue 插件体系图示
使用插件进行批量注册
const locale = locale$1.use;
const defaultInstallOpt = {
size: '',
zIndex: 2000,
};
const install = (app, opt) => {
const option = Object.assign(defaultInstallOpt, opt);
locale(option.locale);
if (option.i18n) {
locale$1.i18n(option.i18n);
}
app.config.globalProperties.$ELEMENT = option;
config.setConfig(option);
//批量注册组件
components.forEach(component => {
app.component(component.name, component);
});
//批量注册插件,插件对象本身就已经附加了 `install` 静态方法。
plugins.forEach(plugin => {
app.use(plugin);
});
};
批量注册主要常用于 UI 组件库。