vue模态框组件实现
Vue 模态框组件实现
方法一:基础模态框组件
创建 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: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('close');
}
}
};
</script>
<style>
.modal {
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #fff;
margin: 15% auto;
padding: 20px;
width: 80%;
max-width: 600px;
position: relative;
}
.close {
position: absolute;
right: 10px;
top: 5px;
cursor: pointer;
font-size: 24px;
}
</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>
方法三:通过 Teleport 实现

Vue 3 可以使用 <Teleport> 将模态框渲染到 body 外层:
<template>
<Teleport to="body">
<div class="modal" v-if="isVisible">
<!-- 内容同上 -->
</div>
</Teleport>
</template>
方法四:过渡动画效果
为模态框添加过渡效果:

<template>
<Transition name="fade">
<div class="modal" v-if="isVisible">
<!-- 内容 -->
</div>
</Transition>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
方法五:全局模态框服务
创建全局可调用的模态框:
// modalService.js
import { createApp } from 'vue';
export default {
install(app) {
app.config.globalProperties.$modal = {
show(options) {
const modalApp = createApp(ModalComponent, options);
const mountNode = document.createElement('div');
document.body.appendChild(mountNode);
modalApp.mount(mountNode);
}
};
}
};
在 main.js 中注册:
import modalService from './modalService';
app.use(modalService);
使用时:
this.$modal.show({
title: '提示',
content: '操作成功'
});






