扩展toast合并popup(按需加载)
上一篇我们对popup进行了扩展,依样画葫芦这里我对toast进行同样的封装。代码如下:
// toast.vue
<template>
<div class="container">
<div class="content">
{{content}}
</div>
</div>
</template>
<script>
export default {
data() {
return {
content: '',
time: 1500
}
},
methods: {
// 移除
destorySelf() {
// 销毁实例 移除事件、指令,删除子实例,但dom依然存在
this.$destroy(true);
// 从dom节点删除
this.$el && this.$el.parentNode.removeChild(this.$el)
}
},
mounted() {
setTimeout(() => {
console.log('destory');
this.destorySelf();
}, this.time);
}
}
</script>
<style>
.container {
position: fixed;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.container .content {
background-color: rgba(0,0,0,.8);
padding: 5px 10px;
max-height: 70%;
font-size: 14px;
color: #FFFFFF;
border-radius: 5px;
}
</style>
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// toast.js
import Vue from 'vue'
import toast from './toast.vue'
const toastSub = Vue.extend(toast)
export function createToast(options){
let time_num = options && typeof options.time == 'number' ? true : false
let m = new toastSub({
data: {
content: options && options.content || '',
time: time_num ? options.time : 1500
}
});
//
let vm = m.$mount();
document.querySelector('#app').appendChild(vm.$el);
return vm;
}
export default {
install: (Vue) => {
Vue.prototype.$toast = createToast;
}
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
这里即使用export导出又使用export default默认导出的原因就是让扩展可以独立使用有可以合并使用。
新建index.js,其中添加如下代码
import Vue from 'vue'
import { createToast } from './toast/toast.js'
import { createModal } from './modal/modal.js'
export default {
install: (Vue) => {
Vue.prototype.$custom = {
toast: createToast,
modal: createModal
}
// 或
// Vue.prototype.$modal = createModal;
// Vue.prototype.$toast = createToast;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
修改main.js中代码如下:
// 全部加载
import custom from './custom' //引入index.js
Vue.use(custom);
// 按需加载
// import modal from './custom/modal/modal.js'
// Vue.use(modal);
1
2
3
4
5
6
7
2
3
4
5
6
7
这里使用按需加载的意义并不大,只是作为一个参考。既然方法可以这样使用,那我们就可以对全局组件的注册进行按需加载和全部加载。
上次更新: 2025/09/05, 8:09:00