vue创建一个body作为父元素的弹窗

分别借鉴elementui的dialog和mint-ui的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
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<template>
<div v-if='visible' class='my-model center-flex'>
<div @click='close' ref='model' class='bg'></div>
<div class='wrapper'>
<slot></slot>
</div>
</div>
</template>

<script>
export default {
props: {
visible: {
type: Boolean,
default: true
},
appendToBody: {
type: Boolean,
default: true
}
},
data() {
return {
}
},
watch: {
visible() {
this.disabledScroll()
}
},
methods: {
close() {
this.$emit('close')
},
initModel() {
if (this.appendToBody) {
document.body.appendChild(this.$el)
}
},
disabledScroll() {
if (this.visible) {
this.$nextTick(() => {
this.$refs.model.ontouchmove = (e) => {
e.preventDefault()
}
})
}
}
},
mounted() {
this.initModel()
this.disabledScroll()
},
beforeDestroy() {
if (this.appendToBody && this.$el && this.$el.parentNode) {
this.$el.parentNode.removeChild(this.$el);
}
}
}
</script>

<style lang='scss' scoped>
.my-model {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

.bg {
display: block;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.3);
position: absolute;
left: 0;
top: 0;
}

.wrapper {
position: relative;
z-index: 1;
background: white;
}
</style>

老版本弹窗

model.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
27
28
import Vue from 'vue'

const Model = Vue.extend(require('./MyModel').default)
let instance

export default {
show(component) {
if (!instance) {
// 第一次创建
instance = new Model({
el: document.createElement('div')
})
document.body.appendChild(instance.$el)
instance.componentName = component
} else {
// 已经创建
if (instance.visible) return
instance.componentName = component
instance.visible = true
}
},

close() {
if (instance) {
instance.visible = false
}
}
}

组件

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
<template>
<div v-if='visible' class='my-model center-flex'>
<div @click='close' ref='model' class='bg'></div>
<div class='wrapper'>
<component v-if='componentName' :is='componentName'></component>
</div>
</div>
</template>

<script>
export default {
data() {
return {
visible: true,
componentName: ''
}
},
methods: {
close() {
this.visible = false
}
},
mounted() {
this.$nextTick(() => {
this.$refs.model.ontouchmove = (e) => {
e.preventDefault()
}
})
}
}
</script>

<style lang='scss' scoped>
.my-model {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
}

.bg {
display: block;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.3);
position: absolute;
left: 0;
top: 0;
}

.wrapper {
position: relative;
z-index: 1;
background: white;
}
</style>