vue实现弹窗效果
使用 Vue 实现弹窗效果
组件化弹窗实现
创建独立的弹窗组件 Modal.vue,通过 v-if 或 v-show 控制显示状态:
<template>
<div class="modal-mask" v-show="show">
<div class="modal-container">
<slot></slot>
<button @click="$emit('close')">关闭</button>
</div>
</div>
</template>
<script>
export default {
props: ['show']
}
</script>
<style>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-container {
background: white;
padding: 20px;
border-radius: 8px;
}
</style>
动态控制弹窗显示
在父组件中通过数据绑定控制弹窗状态:

<template>
<button @click="showModal = true">打开弹窗</button>
<Modal :show="showModal" @close="showModal = false">
<h3>弹窗内容</h3>
<p>这是自定义插槽内容</p>
</Modal>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: { Modal },
data() {
return {
showModal: false
}
}
}
</script>
使用 Vue Teleport 实现
Vue 3 的 Teleport 可以解决弹窗的 DOM 层级问题:
<template>
<button @click="show = true">打开弹窗</button>
<Teleport to="body">
<Modal v-show="show" @close="show = false"/>
</Teleport>
</template>
过渡动画效果
添加 Vue 过渡效果使弹窗更平滑:

<template>
<Transition name="modal">
<Modal v-if="show" @close="show = false"/>
</Transition>
</template>
<style>
.modal-enter-active,
.modal-leave-active {
transition: opacity 0.3s ease;
}
.modal-enter-from,
.modal-leave-to {
opacity: 0;
}
</style>
全局弹窗服务
创建可复用的弹窗服务(适用于 Vue 3):
// modalService.js
import { createApp } from 'vue'
import Modal from './Modal.vue'
export function showModal(options) {
const mountNode = document.createElement('div')
document.body.appendChild(mountNode)
const app = createApp(Modal, {
...options,
onClose: () => {
app.unmount()
document.body.removeChild(mountNode)
}
})
app.mount(mountNode)
}
调用方式:
import { showModal } from './modalService'
showModal({
title: '系统提示',
content: '操作成功',
onConfirm: () => console.log('确认')
})






