vue实现全局遮罩层
实现全局遮罩层的方案
在Vue中实现全局遮罩层可以通过以下两种常见方式:
方案一:使用动态组件挂载
创建独立的遮罩层组件(如GlobalMask.vue):

<template>
<div v-if="visible" class="global-mask">
<!-- 遮罩内容 -->
</div>
</template>
<script>
export default {
data() {
return {
visible: false
}
},
methods: {
show() {
this.visible = true
},
hide() {
this.visible = false
}
}
}
</script>
<style scoped>
.global-mask {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0, 0, 0, 0.5);
z-index: 9999;
}
</style>
通过插件方式全局注册:
// maskPlugin.js
import Vue from 'vue'
import MaskComponent from './GlobalMask.vue'
const Mask = {
install(Vue) {
const MaskConstructor = Vue.extend(MaskComponent)
const instance = new MaskConstructor()
instance.$mount(document.createElement('div'))
document.body.appendChild(instance.$el)
Vue.prototype.$mask = {
show: () => instance.show(),
hide: () => instance.hide()
}
}
}
Vue.use(Mask)
方案二:使用Vuex状态管理
定义Vuex状态:

// store.js
export default new Vuex.Store({
state: {
showMask: false
},
mutations: {
SET_MASK(state, payload) {
state.showMask = payload
}
}
})
在根组件中使用:
<template>
<div>
<div v-if="$store.state.showMask" class="global-mask"></div>
<router-view/>
</div>
</template>
调用方式:
// 显示遮罩
this.$store.commit('SET_MASK', true)
// 隐藏遮罩
this.$store.commit('SET_MASK', false)
样式优化建议
.global-mask {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.6);
z-index: 1000;
display: flex;
justify-content: center;
align-items: center;
}
/* 添加加载动画示例 */
.mask-spinner {
width: 40px;
height: 40px;
border: 4px solid #fff;
border-radius: 50%;
border-top-color: transparent;
animation: spin 1s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
注意事项
- 遮罩层的z-index需要确保高于页面其他元素
- 移动端需要考虑viewport单位兼容性
- 长时间显示遮罩时应添加超时自动隐藏逻辑
- 多个遮罩同时出现时需要处理层级关系






