vue自己实现模态框
实现模态框的基本结构
在Vue中实现模态框,可以通过组件化的方式构建。模态框通常包含遮罩层、内容区域以及关闭按钮。
<template>
<div class="modal" v-if="isVisible">
<div class="modal-mask" @click="close"></div>
<div class="modal-container">
<div class="modal-header">
<h3>{{ title }}</h3>
<button class="modal-close" @click="close">×</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button @click="close">关闭</button>
</div>
</div>
</div>
</template>
控制模态框的显示与隐藏
通过v-if或v-show控制模态框的显示状态,结合props和自定义事件实现交互逻辑。
<script>
export default {
props: {
isVisible: {
type: Boolean,
default: false
},
title: {
type: String,
default: '模态框标题'
}
},
methods: {
close() {
this.$emit('close');
}
}
};
</script>
添加样式增强视觉效果
模态框的样式需要确保其居中显示,并添加遮罩层实现视觉隔离效果。
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-mask {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-container {
position: relative;
background: white;
border-radius: 8px;
min-width: 300px;
z-index: 1001;
}
.modal-header {
padding: 16px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-body {
padding: 16px;
}
.modal-footer {
padding: 16px;
border-top: 1px solid #eee;
text-align: right;
}
.modal-close {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
}
</style>
在父组件中使用模态框
父组件通过控制状态变量来显示或隐藏模态框,并监听关闭事件。
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<custom-modal
:isVisible="showModal"
title="自定义标题"
@close="showModal = false"
>
<p>这里是模态框的内容</p>
</custom-modal>
</div>
</template>
<script>
import CustomModal from './CustomModal.vue';
export default {
components: {
CustomModal
},
data() {
return {
showModal: false
};
}
};
</script>
支持动画效果
通过Vue的过渡系统为模态框添加淡入淡出效果,增强用户体验。
<template>
<transition name="fade">
<div class="modal" v-if="isVisible">
<!-- 模态框内容 -->
</div>
</transition>
</template>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
实现可配置的模态框宽度和高度
通过props传递宽度和高度参数,使模态框尺寸可定制化。
props: {
width: {
type: String,
default: 'auto'
},
height: {
type: String,
default: 'auto'
}
}
<div class="modal-container" :style="{ width: width, height: height }">
<!-- 模态框内容 -->
</div>






