vue 组件实现 遮罩
Vue 组件实现遮罩层
遮罩层(Overlay)是常见的 UI 组件,用于在页面上覆盖半透明背景,通常配合弹窗、菜单等使用。以下是几种实现方式:
基础遮罩组件
通过固定定位和半透明背景实现基础遮罩:

<template>
<div v-if="visible" class="overlay" @click.self="handleClose">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
visible: Boolean
},
methods: {
handleClose() {
this.$emit('close')
}
}
}
</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;
align-items: center;
justify-content: center;
}
</style>
动画遮罩
添加过渡动画效果:

<template>
<transition name="fade">
<div v-if="visible" class="overlay" @click.self="handleClose">
<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>
可配置遮罩
扩展组件支持更多配置选项:
<script>
export default {
props: {
visible: Boolean,
clickClose: {
type: Boolean,
default: true
},
backgroundColor: {
type: String,
default: 'rgba(0, 0, 0, 0.5)'
},
zIndex: {
type: Number,
default: 999
}
},
methods: {
handleClose() {
if (this.clickClose) {
this.$emit('close')
}
}
}
}
</script>
<style scoped>
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: v-bind(backgroundColor);
z-index: v-bind(zIndex);
}
</style>
全局遮罩服务
创建可编程控制的遮罩服务:
// overlay.service.js
import Vue from 'vue'
const OverlayComponent = Vue.extend({
template: `
<div class="overlay" :style="{ zIndex }">
<slot></slot>
</div>
`,
props: {
zIndex: {
type: Number,
default: 999
}
}
})
export default {
show(content, options = {}) {
const instance = new OverlayComponent({
propsData: options
})
if (content) {
instance.$slots.default = [content]
}
instance.$mount()
document.body.appendChild(instance.$el)
return instance
}
}
使用示例
<template>
<button @click="showOverlay">显示遮罩</button>
<Overlay :visible="isVisible" @close="isVisible = false">
<div class="modal-content">这里是弹窗内容</div>
</Overlay>
</template>
<script>
import Overlay from './Overlay.vue'
export default {
components: { Overlay },
data() {
return {
isVisible: false
}
},
methods: {
showOverlay() {
this.isVisible = true
}
}
}
</script>
这些实现方式可根据项目需求选择或组合使用,基础组件适合简单场景,全局服务适合复杂应用。






