vue 组件实现 遮罩
Vue 组件实现遮罩层
遮罩层(Overlay)常用于模态框、加载状态或全屏提示等场景。以下是几种实现方式:
基础遮罩组件
通过固定定位和半透明背景实现遮罩效果:

<template>
<div v-if="visible" class="overlay" @click.self="handleClose">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
closable: {
type: Boolean,
default: true
}
},
methods: {
handleClose() {
if (this.closable) this.$emit('update:visible', false)
}
}
}
</script>
<style scoped>
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
display: flex;
justify-content: center;
align-items: center;
}
</style>
动画过渡效果
添加过渡动画增强用户体验:

<template>
<transition name="fade">
<div v-if="visible" class="overlay">
<slot></slot>
</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
与模态框结合使用
典型的使用场景示例:
<template>
<div>
<button @click="showModal = true">打开模态框</button>
<Overlay v-model="showModal">
<div class="modal-content">
<h3>标题</h3>
<p>内容区域...</p>
<button @click="showModal = false">关闭</button>
</div>
</Overlay>
</div>
</template>
<style>
.modal-content {
background: white;
padding: 20px;
border-radius: 8px;
}
</style>
高级功能扩展
支持更多自定义选项的版本:
<script>
export default {
props: {
visible: Boolean,
zIndex: {
type: Number,
default: 999
},
backgroundColor: {
type: String,
default: 'rgba(0, 0, 0, 0.5)'
},
blur: {
type: Boolean,
default: false
}
},
computed: {
overlayStyle() {
return {
'z-index': this.zIndex,
'background-color': this.backgroundColor,
'backdrop-filter': this.blur ? 'blur(2px)' : 'none'
}
}
}
}
</script>
注意事项
- 确保遮罩层的
z-index高于页面其他元素 - 移动端需考虑
viewport相关样式 - 内容滚动时可能需要阻止背景滚动
- 多次调用时需管理
z-index的堆叠顺序






