Vue自定义全局组件
vue自定义全局弹框组件
在components文件夹下新增一个组件文件夹Dialog,新建一个模板组件Dialog.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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110<template>
<div class="u_dialog_panel" @touchmove.stop="noop">
<div class="mask" v-if="visible" @click="handleClose"></div>
<transition name="open">
<div v-if="visible" class="dialog_body">
<slot></slot>
<div class="btns" v-if="confirmText || cancleText">
<div class="cancle btn" v-if="cancleText" @click="handleCancle">{{cancleText}}</div>
<div class="confirm btn" :style="confirmStyle" v-if="confirmText" @click="handleConfirm">{{confirmText}}</div>
</div>
</div>
</transition>
</div>
</template>
<script>
export default {
name: 'UDialog',
props: {
visible: { type: Boolean, default: false, required: true },
// 确定按钮的文案
confirmText: { type: String, default: '确定' },
confirmStyle: { type: String, default: '' },
// 取消按钮的文案
cancleText: { type: String, default: '取消' },
cancleStyle: { type: String, default: '' },
},
created () {
this.$nextTick(() => {
document.body.insertBefore(this.$el, document.body.lastChild)
})
},
beforeDestroy () {
document.body.removeChild(this.$el)
},
methods: {
// 关闭弹窗
handleClose () { this.$emit('close') },
// 确定按钮
handleConfirm () { this.$emit('confirm') },
// 取消按钮
handleCancle () { this.$emit('cancle') },
noop () {}
}
}
</script>
<style lang="less" scoped>
.u_dialog_panel {
.mask {
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
position: fixed;
left: 0;
top: 0;
z-index: 100;
backdrop-filter: blur(5px);
}
.dialog_body{
width: 80vw;
background-color: #fff;
position: fixed;
left: 50vw;
top: 50vh;
z-index: 100;
transform: translate(-50%, -50%);
transform-origin: 0 0;
border-radius: .875rem;
&.open-enter {
opacity: 0;
transform: scale(0.7) translate(-50%, -50%);
transition: all 0.3s;
}
&.open-enter-to {
opacity: 1;
transform: scale(1) translate(-50%, -50%);
transition: all 0.3s;
}
.btns {
display: flex;
justify-content: space-between;
align-items: center;
.btn {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
width: 50%;
height: 2.875rem;
border-top: 1px solid #ddd;
box-sizing: border-box;
display: flex;
justify-content: center;
align-items: center;
font-size: .875rem;
& + .btn {
border-left: 1px solid #ddd;
}
&.cancle {
color: #666666;
}
&.confirm {
color: #FF5883;
}
}
}
}
}
</style>在此文件夹再新建一个index.js
1
2
3
4
5
6
7
8import Dialog from './Dialog'
Dialog.install = function (Vue, options) {
Vue.component(`${Dialog.name}`, Dialog)
}
export default Dialog最后再main.js里注册为全局组件
1
2
3import Dialog from './components/Dialog/index.js'
Vue.use(Dialog)
这样就可以在其他组件里无需声明而使用此组件
Vue自定义全局组件
https://zouhualu.github.io/20210618/Vue自定义全局组件/