vue实现模态功能
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: 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;
border: 1px solid #888;
width: 80%;
max-width: 600px;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
</style>
在父组件中使用:
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<Modal :isVisible="showModal" @close="showModal = false">
<h3>模态框标题</h3>
<p>模态框内容...</p>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: { Modal },
data() {
return {
showModal: false
};
}
};
</script>
使用第三方库实现模态框
安装 vue-final-modal 库:
npm install vue-final-modal
使用示例:
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<vue-final-modal v-model="showModal">
<div class="modal-content">
<h3>模态框标题</h3>
<p>模态框内容...</p>
<button @click="showModal = false">关闭</button>
</div>
</vue-final-modal>
</div>
</template>
<script>
import { VueFinalModal } from 'vue-final-modal';
export default {
components: { VueFinalModal },
data() {
return {
showModal: false
};
}
};
</script>
动态控制模态框内容
通过插槽和 props 传递动态内容:
<Modal :isVisible="showModal" @close="showModal = false">
<h3>{{ modalTitle }}</h3>
<p>{{ modalContent }}</p>
<button @click="handleConfirm">确认</button>
</Modal>
在父组件中定义数据和方法:
data() {
return {
showModal: false,
modalTitle: '确认操作',
modalContent: '确定要执行此操作吗?'
};
},
methods: {
handleConfirm() {
// 处理确认逻辑
this.showModal = false;
}
}
模态框动画效果
添加过渡动画:
<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, .fade-leave-to {
opacity: 0;
}
</style>
可复用模态框服务
创建全局模态框服务:
// modalService.js
import Vue from 'vue';
import Modal from './Modal.vue';
const ModalConstructor = Vue.extend(Modal);
const modalService = {
open(options) {
const instance = new ModalConstructor({
propsData: options.props
});
instance.$slots.default = [options.content];
instance.$mount();
document.body.appendChild(instance.$el);
return instance;
}
};
export default modalService;
在任何组件中使用:

import modalService from './modalService';
// 打开模态框
const modal = modalService.open({
props: { title: '提示' },
content: '这是一个全局模态框'
});
// 关闭模态框
modal.close();






