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