vue实现遮罩
Vue 实现遮罩的方法
在 Vue 中实现遮罩通常用于模态框、弹窗或加载状态。以下是几种常见的实现方式:
使用 CSS 和 Vue 动态类
通过 Vue 的 v-bind:class 或 v-if 动态控制遮罩的显示与隐藏。
<template>
<div>
<button @click="showMask = true">显示遮罩</button>
<div v-if="showMask" class="mask" @click="showMask = false"></div>
</div>
</template>
<script>
export default {
data() {
return {
showMask: false
}
}
}
</script>
<style>
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
</style>
结合过渡动画
通过 Vue 的 <transition> 组件为遮罩添加淡入淡出效果。
<template>
<div>
<button @click="showMask = true">显示遮罩</button>
<transition name="fade">
<div v-if="showMask" class="mask" @click="showMask = false"></div>
</transition>
</div>
</template>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
</style>
通过组件封装
将遮罩封装为可复用的组件,便于在多个地方调用。
<!-- Mask.vue -->
<template>
<transition name="fade">
<div v-if="visible" class="mask" @click="$emit('close')"></div>
</transition>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
}
}
</script>
<style>
.mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
使用第三方库
对于更复杂的需求,可以使用如 vue-js-modal 等第三方库快速实现遮罩效果。

npm install vue-js-modal
<template>
<button @click="showModal">显示遮罩</button>
</template>
<script>
import VModal from 'vue-js-modal'
export default {
methods: {
showModal() {
this.$modal.show('example-modal')
}
}
}
</script>
注意事项
- 遮罩的
z-index应高于页面其他元素,但低于弹窗内容。 - 遮罩通常需要设置为
position: fixed以覆盖整个视口。 - 点击遮罩时通常会关闭弹窗或遮罩本身,可通过事件处理实现。






