vue 组件实现 遮罩
Vue 组件实现遮罩层的方法
基础遮罩层实现
创建一个简单的遮罩层组件,使用绝对定位覆盖整个视口。以下是一个基础实现:
<template>
<div class="mask" v-if="visible" @click="handleClick"></div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
},
clickToClose: {
type: Boolean,
default: true
}
},
methods: {
handleClick() {
if (this.clickToClose) {
this.$emit('update:visible', false)
}
}
}
}
</script>
<style scoped>
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
}
</style>
带内容的遮罩层
扩展基础遮罩层,使其可以包含自定义内容:

<template>
<div class="mask" v-if="visible" @click.self="handleClick">
<div class="mask-content">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
},
clickToClose: {
type: Boolean,
default: true
}
},
methods: {
handleClick() {
if (this.clickToClose) {
this.$emit('update:visible', false)
}
}
}
}
</script>
<style scoped>
.mask {
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;
}
.mask-content {
background: white;
padding: 20px;
border-radius: 4px;
}
</style>
动画过渡效果
为遮罩层添加淡入淡出动画效果:
<template>
<transition name="fade">
<div class="mask" v-if="visible" @click.self="handleClick">
<div class="mask-content">
<slot></slot>
</div>
</div>
</transition>
</template>
<style scoped>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
全局遮罩层服务
创建一个可以在任何地方调用的遮罩层服务:

// maskService.js
import Vue from 'vue'
import Mask from './Mask.vue'
const MaskConstructor = Vue.extend(Mask)
let maskInstance = null
export default {
show(options = {}) {
if (!maskInstance) {
maskInstance = new MaskConstructor({
el: document.createElement('div'),
propsData: options
})
document.body.appendChild(maskInstance.$el)
}
maskInstance.visible = true
},
hide() {
if (maskInstance) {
maskInstance.visible = false
}
}
}
使用示例
在组件中使用遮罩层:
<template>
<button @click="showMask">显示遮罩</button>
<Mask :visible.sync="isMaskVisible">
<div>自定义内容</div>
</Mask>
</template>
<script>
import Mask from './Mask.vue'
export default {
components: { Mask },
data() {
return {
isMaskVisible: false
}
},
methods: {
showMask() {
this.isMaskVisible = true
}
}
}
</script>
或者使用全局服务:
import maskService from './maskService'
// 显示遮罩
maskService.show()
// 隐藏遮罩
maskService.hide()






