vue实现弹窗组件
Vue 弹窗组件的实现方法
基础弹窗组件实现
创建一个名为Modal.vue的组件文件,包含模板、样式和逻辑:
<template>
<div class="modal-mask" v-show="visible" @click.self="close">
<div class="modal-container">
<div class="modal-header">
<slot name="header"></slot>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false)
}
}
}
</script>
<style>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 999;
}
.modal-container {
background: white;
padding: 20px;
border-radius: 4px;
min-width: 300px;
}
</style>
使用弹窗组件
在父组件中引入并使用弹窗:

<template>
<button @click="showModal = true">打开弹窗</button>
<Modal v-model:visible="showModal">
<template #header>
<h3>标题</h3>
</template>
<p>弹窗内容</p>
<template #footer>
<button @click="showModal = false">关闭</button>
</template>
</Modal>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: { Modal },
data() {
return {
showModal: false
}
}
}
</script>
动画效果增强
为弹窗添加过渡动画:
<template>
<transition name="modal">
<div class="modal-mask" v-show="visible" @click.self="close">
<!-- 其余内容不变 -->
</div>
</transition>
</template>
<style>
.modal-enter-active, .modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from, .modal-leave-to {
opacity: 0;
}
.modal-container {
transition: transform 0.3s ease;
}
.modal-enter-active .modal-container {
animation: bounce-in 0.3s;
}
.modal-leave-active .modal-container {
animation: bounce-in 0.3s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0.95);
}
50% {
transform: scale(1.05);
}
100% {
transform: scale(1);
}
}
</style>
全局弹窗服务
创建可编程调用的全局弹窗:

// modalService.js
import { createApp, h } from 'vue'
export function showModal(options) {
const div = document.createElement('div')
document.body.appendChild(div)
const app = createApp({
render() {
return h(Modal, {
visible: true,
onClose: () => {
app.unmount()
div.remove()
},
...options
})
}
})
app.mount(div)
}
使用全局弹窗:
import { showModal } from './modalService'
showModal({
title: '全局弹窗',
content: '通过服务调用的弹窗',
onConfirm() {
console.log('确认操作')
}
})
可复用配置选项
扩展弹窗组件支持更多配置:
<script>
export default {
props: {
title: String,
showClose: {
type: Boolean,
default: true
},
width: {
type: String,
default: '50%'
},
beforeClose: Function
},
methods: {
close() {
if (this.beforeClose) {
this.beforeClose(() => {
this.doClose()
})
} else {
this.doClose()
}
},
doClose() {
this.$emit('update:visible', false)
}
}
}
</script>






