vue 开发一个插件Toast

Vue.js 的插件应当有一个公开方法 install 。这个方法的第一个参数是 Vue 构造器 , 第二个参数是一个可选的选项对象。

1.toast.js

// 1.定义插件对象
var Toast = {}
// 2.vue开发插件有一个公开方法 install
// 传一个固定的Vue和初始化配置options
Toast.install = function(Vue, options){
	// 3.定义配置项
	let opt = {
		defaultType: 'bottom',
		duration: '2500'
	}
	// 4.覆盖配置项
	for(let property in options){
		opt[property] = options[property]
	}
	// 5.挂载一个vue调用方法
	Vue.prototype.$toastme = (tips, type) =>{
		if(type){
			opt.defaultType = type
		}
		// 还没消失dom不执行
		if(document.getElementsByClassName('vue-toast').length){
			return;
		}
		// 6.建构dom
		let toastTpl = Vue.extend({
			template: '<div class="vue-toast toast-'+ opt.defaultType +'">' + tips + '</div>'
		})
		let tpl = new toastTpl().$mount().$el;
		document.body.appendChild(tpl);
		setTimeout(function(){
			document.body.removeChild(tpl);
		},opt.duration)
	}
	// 7.返回不同位置
	['bottom', 'center', 'top'].forEach(type =>{
		Vue.prototype.$toastme[type] = (tips) =>{
			return Vue.prototype.$toastme[type](tips, type)
		}
	})
}
// 8.导出
module.exports = Toast;

2.main.js

// vue挂载插件
Vue.use(Toast,{defaultType:'top'})

3.index.vue

// 使用插件
this.$toastme(11);

参考:https://juejin.im/post/58d9aae02f301e007e8ee278

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值