Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
以上是官方文档部分
我们这里要说的是第4种方式,以及整个插件的完成生命周期
以弹框这种需要UI的插件为例
import template from 'template.vue'
function render(Vue, options, methodOptions) {
// 下面的几种方式均从这里开始
}
export default {
install:(Vue, options)=>{
// 处理装载的时候传入参数
Vue.prototype.$myMethod = function (methodOptions) {
render(Vue, options, methodOptions);
}
}
}
new Vue
function render(Vue, options, methodOptions) {
const {store={}} = options;
const comp = new Vue({
name: `Root${template.name}`,
store,
data() {
return {
options: { ...methodOptions }
};
},
render(h: any) {
return h(template, {
props: this.options
});
}
});
comp.$mount();
document.body.appendChild(comp.$el);
comp.$children[0].show && comp.$children[0].show();
// 如果template中设置了关闭销毁的话 后续在使用show和close则是则失效
// 在template中如果想要close之后移除dom需要this.$destroy();this.$el.remove();
return {
show: () => {comp.$children[0].show && comp.$children[0].show()},
close: () => {comp.$children[0].close && comp.$children[0].close()}
};
}
Vue.extend
使用vue.extend返回一个子类构造函数,也就是预设部分选项的vue实例构造器。
后可使用vue.component进行实例化、或使用new extendName().$mount(’’+el)方式进行实例化(从而实现模拟组件)。
function render(Vue, options, methodOptions) {
const TemplateConstructor = Vue.extend(template);
const instance = new TemplateConstructor({
el: document.createElement('div'),
propsData: methodOptions,
});
document.body.appendChild(instance.$el);
document.body.appendChild(instance.$el);
instance.show && instance.show();
return {
close: () => {instance.close && instance.close()},
show: () => {instance.show && instance.show()}
};
}
还有其他方式请留言一起讨论