toast弹框组件的封装-插件方式

我们这里打算做一个弹框功能

当我们点击加入购物车的时候 就会弹出这个弹框,把它做成插件方式的好处,我们引用的时候就很简单,只需要用this.$toast就可以了,

首先我们要写一个插件

 1 <template>
 2     <div class="toast" v-show="isShow">
 3         <div>{{message}}</div>
 4     </div>
 5 </template>
 6     <script>
 7         export default {
 8             name: "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上引入这个插件

 
import toast from 'components/common/toast'
Vue.use(toast)
然后我们就可以直接在插件中引用
 that.$toast.show("这里添加内容”, 2000)

  

 
 
 
posted @ 2020-09-22 11:48  Cookie饼干  阅读(251)  评论(0编辑  收藏  举报