vue 封装一个toast组件
第一步 创建一个toast.vue
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39<template> <transition name="fade"> <div v-show="visible">{{message}}</div> </transition> </template> <script> export default { data () { return { visible: false, message: '' } } } </script> <style scoped> div { padding: 15px 30px; color: #fff; background-color: rgba(0, 0, 0, 0.6); text-align: center; position: fixed; top: 30%; left: 50%; transform: translate(-50%, -50%); } /* vue动画过渡效果设置 */ .fade-enter-active, .fade-leave-active { transition: opacity .5s; } .fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ { opacity: 0; } </style>
第二步 创建一个index.js
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27import ToastComponent from './toast.vue' const Toast = { install: function (Vue) { // 创建一个Vue的“子类”组件 const ToastConstructor = Vue.extend(ToastComponent) // 创建一个该子类的实例,并挂载到一个元素上 const instance = new ToastConstructor() // 将这个实例挂载到动态创建的元素上,并将元素添加到全局结构中 instance.$mount(document.createElement('div')) document.body.appendChild(instance.$el) // 在Vue的原型链上注册方法,控制组件 Vue.prototype.$toast = (msg, duration = 1500) => { instance.message = msg instance.visible = true setTimeout(() => { instance.visible = false }, duration) } } } export default Toast
第三步 main.js
复制代码
1
2
3import Toast from './components/toast/index' Vue.use(Toast)
第四步:在组件中使用
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30<template> <div class="home"> <button @click="go">点击</button> </div> </template> <script> export default { name: "Home", components: {}, data: function() { return {}; }, mounted() {}, methods: { go() { this.$toast("加载中"); } } }; </script> <style scoped> .home { width: 100%; height: 100vh; background-color: pink; } </style>
最后
以上就是舒服火龙果最近收集整理的关于vue 封装一个toast组件的全部内容,更多相关vue内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复