vue插件plugins的几种写法

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()}
    };
}

还有其他方式请留言一起讨论

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值