vue自己实现模态框
实现模态框的基本结构
在Vue中实现模态框,可以通过组件化方式封装。创建一个Modal.vue文件,定义模态框的模板、样式和逻辑。模态框通常包含遮罩层、内容区域、关闭按钮等元素。
<template>
<div class="modal-mask" v-show="visible" @click.self="close">
<div class="modal-container">
<div class="modal-header">
<slot name="header"></slot>
<button class="modal-close" @click="close">×</button>
</div>
<div class="modal-body">
<slot name="body"></slot>
</div>
<div class="modal-footer">
<slot name="footer"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false);
}
}
};
</script>
<style scoped>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.modal-container {
background: white;
border-radius: 4px;
min-width: 300px;
max-width: 80%;
}
.modal-header {
padding: 16px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
}
.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>
使用模态框组件
在父组件中引入并使用模态框,通过v-model控制显示隐藏状态。可以利用插槽自定义模态框内容。
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<Modal v-model="showModal">
<template #header>
<h3>自定义标题</h3>
</template>
<template #body>
<p>这里是模态框内容</p>
</template>
<template #footer>
<button @click="showModal = false">关闭</button>
</template>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: { Modal },
data() {
return {
showModal: false
};
}
};
</script>
添加动画效果
为模态框添加淡入淡出动画,增强用户体验。使用Vue的过渡组件包裹模态框。
<template>
<transition name="modal-fade">
<div class="modal-mask" v-show="visible" @click.self="close">
<!-- 其余代码不变 -->
</div>
</transition>
</template>
<style scoped>
.modal-fade-enter-active,
.modal-fade-leave-active {
transition: opacity 0.3s;
}
.modal-fade-enter,
.modal-fade-leave-to {
opacity: 0;
}
</style>
处理滚动锁定
模态框显示时锁定页面滚动,防止背景内容滚动。通过动态添加移除CSS类实现。
// 在Modal.vue的script部分
watch: {
visible(newVal) {
if (newVal) {
document.body.classList.add('modal-open');
} else {
document.body.classList.remove('modal-open');
}
}
}
/* 全局样式 */
.modal-open {
overflow: hidden;
}
支持ESC键关闭
监听键盘事件,按下ESC键时关闭模态框。在组件挂载和销毁时添加移除事件监听。
// 在Modal.vue的script部分
mounted() {
document.addEventListener('keydown', this.handleKeydown);
},
beforeDestroy() {
document.removeEventListener('keydown', this.handleKeydown);
},
methods: {
handleKeydown(e) {
if (e.key === 'Escape' && this.visible) {
this.close();
}
}
}
响应式宽度控制
根据不同屏幕尺寸调整模态框宽度,确保在小屏幕上良好显示。
.modal-container {
width: 50%;
}
@media (max-width: 768px) {
.modal-container {
width: 90%;
}
}






