toast彈框元件的封裝-外掛方式
阿新 • • 發佈:2020-09-22
我們這裡打算做一個彈框功能
當我們點選加入購物車的時候 就會彈出這個彈框,把它做成外掛方式的好處,我們引用的時候就很簡單,只需要用this.$toast就可以了,
首先我們要寫一個外掛
1 <template> 2 <div class="toast" v-show="isShow"> 3 <div>{{message}}</div> 4 </div> 5 </template> 6 <script> 7 export default { 8name: "Toast", 9 data() { 10 return { 11 message: '', 12 isShow: false 13 } 14 }, 15 methods: { 16 show(message,duration) { 17 this.isShow = true ;18 this.message= message; 19 setTimeout(()=>{ 20 this.isShow = false; 21 this.message = '' 22 },duration) 23 } 24 } 25 } 26 </script> 27 <style scoped> 28.toast { 29 position: fixed; 30 top: 50%; 31 left: 50%; 32 transform: translate(-50%, -50%); 33 padding: 8px 10px; 34 color: #fff; 35 background-color: rgba(0, 0, 0, .75); 36 z-index: 999; 37 } 38 </style>
然後我們需要根據這個元件構建元件物件,並把這個物件上傳到Vue.prototype上去 方便每個元件的使用
1 import Toast from './Toast' 2 const obj = {} 3 obj.install = function (Vue) { 4 //1.建立元件構造器 5 const toastContrustor = Vue.extend(Toast) 6 //2.new的方式,根據元件構造器,可以創建出一個元件物件 7 const toast = new toastContrustor() 8 //3.將元件物件,手動掛載到某一個元素上 9 toast.$mount(document.createElement('div')) 10 //4.toast.$el對應的就是div 11 document.body.appendChild(toast.$el) 12 13 Vue.prototype.$toast = toast; 14 } 15 export default obj
然後我們需要在main.js上引入這個外掛
importtoastfrom'components/common/toast' Vue.use(toast) 然後我們就可以直接在外掛中引用that.$toast.show("這裡新增內容”, 2000)