vue 实现modal
Vue 实现 Modal 弹窗的方法
使用 Vue 原生组件实现
创建一个可复用的 Modal 组件,通过 v-if 或 v-show 控制显示/隐藏,结合 props 和 emit 实现数据传递和事件交互。
<!-- Modal.vue -->
<template>
<div class="modal" v-if="isVisible">
<div class="modal-content">
<span class="close" @click="close">×</span>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
isVisible: Boolean
},
methods: {
close() {
this.$emit('close');
}
}
};
</script>
<style>
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
width: 80%;
}
.close {
float: right;
cursor: pointer;
}
</style>
父组件调用方式:
<template>
<button @click="showModal = true">打开弹窗</button>
<Modal :isVisible="showModal" @close="showModal = false">
<h2>弹窗标题</h2>
<p>弹窗内容</p>
</Modal>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: { Modal },
data() {
return { showModal: false }
}
};
</script>
使用 Vue Teleport 实现
Vue 3 的 <Teleport> 可以将模态框渲染到 body 根节点,避免样式层级问题:
<template>
<Teleport to="body">
<div class="modal" v-if="isVisible">
<!-- 内容同上 -->
</div>
</Teleport>
</template>
使用第三方库
-
Vuetify 的
v-dialog:<template> <v-dialog v-model="dialog" width="500"> <template v-slot:activator="{ on }"> <v-btn v-on="on">打开弹窗</v-btn> </template> <v-card> <v-card-title>标题</v-card-title> <v-card-text>内容</v-card-text> </v-card> </v-dialog> </template> -
Element UI 的
el-dialog:<template> <el-button @click="dialogVisible = true">打开弹窗</el-button> <el-dialog :visible.sync="dialogVisible"> <span>内容</span> </el-dialog> </template>
动画效果
通过 Vue 的 <transition> 添加动画:
<transition name="fade">
<Modal v-if="showModal" @close="showModal = false" />
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
注意事项
- 模态框应添加
esc键关闭功能 - 滚动条锁定防止背景滚动
- 焦点管理确保可访问性
- 避免多层模态框叠加导致的 z-index 冲突







