Vue.js 插件开发详解

2020-06-13 10:31:44易采站长站整理

let toastTpl = Vue.extend({ // 1、创建构造器,定义好提示信息的模板
template: '<div class="vue-toast">' + tips + '</div>'
});
let tpl = new toastTpl().$mount().$el; // 2、创建实例,挂载到文档以后的地方
document.body.appendChild(tpl); // 3、把创建的实例添加到body中
setTimeout(function () { // 4、延迟2.5秒后移除该提示
document.body.removeChild(tpl);
}, 2500)
}
}
module.exports = Toast;

好像很简单,我们就实现了 this.$toast() ,接下来显示不同位置。


// toast.js
['bottom', 'center', 'top'].forEach(type => {
Vue.prototype.$toast[type] = (tips) => {
return Vue.prototype.$toast(tips,type)
}
})

这里把 type 传给 $toast 在该方法里进行不同位置的处理,上面说了通过添加不同的类名(toast-bottom、toast-top、toast-center)来实现,那 $toast 方法需要小小修改一下。


Vue.prototype.$toast = (tips,type) => { // 添加 type 参数
let toastTpl = Vue.extend({ // 模板添加位置类
template: '<div class="vue-toast toast-'+ type +'">' + tips + '</div>'
});
...
}

好像差不多了。但是如果我想默认在顶部显示,我每次都要调用 this.$toast.top() 好像就有点多余了,我能不能 this.$toast() 就直接在我想要的地方呢?还有我不想要 2.5s 后才消失呢?这时候注意到 Toast.install(Vue,options) 里的 options 参数,我们可以在 Vue.use() 通过 options 传进我们想要的参数。最后修改插件如下:


var Toast = {};
Toast.install = function (Vue, options) {
let opt = {
defaultType:'bottom', // 默认显示位置
duration:'2500' // 持续时间
}
for(let property in options){
opt[property] = options[property]; // 使用 options 的配置
}
Vue.prototype.$toast = (tips,type) => {
if(type){
opt.defaultType = type; // 如果有传type,位置则设为该type
}
if(document.getElementsByClassName('vue-toast').length){
// 如果toast还在,则不再执行
return;
}
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)
}
['bottom', 'center', 'top'].forEach(type => {
Vue.prototype.$toast[type] = (tips) => {
return Vue.prototype.$toast(tips,type)
}
})
}
module.exports = Toast;

这样子一个简单的 vue 插件就实现了,并且可以通过 npm 打包发布,下次就可以使用 npm install 来安装了。