vue实现弹窗遮罩
Vue实现弹窗遮罩的方法
基础弹窗遮罩实现
通过v-if或v-show控制弹窗显示,遮罩层使用固定定位覆盖全屏。弹窗内容通过z-index置于遮罩层上方。
<template>
<div>
<button @click="showModal = true">打开弹窗</button>
<div v-if="showModal" class="modal-mask">
<div class="modal-container">
<div class="modal-header">
<h3>标题</h3>
<button @click="showModal = false">×</button>
</div>
<div class="modal-body">
弹窗内容
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
}
}
}
</script>
<style>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 9998;
}
.modal-container {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
z-index: 9999;
min-width: 300px;
}
.modal-header {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
</style>
使用Vue过渡动画
添加弹窗显示/隐藏的过渡效果,增强用户体验。
<template>
<transition name="modal">
<div v-if="showModal" class="modal-mask">
<!-- 弹窗内容 -->
</div>
</transition>
</template>
<style>
.modal-enter-active, .modal-leave-active {
transition: opacity 0.3s;
}
.modal-enter, .modal-leave-to {
opacity: 0;
}
</style>
通过组件封装实现复用
将弹窗组件化,通过props接收内容和配置,通过emit触发关闭事件。
<!-- Modal.vue -->
<template>
<transition name="modal">
<div v-if="show" class="modal-mask" @click.self="close">
<div class="modal-container">
<slot></slot>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
show: Boolean
},
methods: {
close() {
this.$emit('close')
}
}
}
</script>
<!-- 使用组件 -->
<Modal :show="showModal" @close="showModal = false">
<div>自定义弹窗内容</div>
</Modal>
阻止背景滚动
弹窗显示时禁止页面滚动,提升交互体验。
methods: {
toggleBodyScroll(showModal) {
document.body.style.overflow = showModal ? 'hidden' : ''
}
},
watch: {
showModal(newVal) {
this.toggleBodyScroll(newVal)
}
}
使用Vuex管理弹窗状态
多个组件需要共享弹窗状态时,可使用Vuex集中管理。
// store.js
export default new Vuex.Store({
state: {
modalVisible: false
},
mutations: {
setModalVisible(state, visible) {
state.modalVisible = visible
}
}
})
// 组件中使用
this.$store.commit('setModalVisible', true)






