vue 開發一個外掛Toast
阿新 • • 發佈:2019-02-20
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);