vue实现弹框遮罩, 点击其他区域弹框关闭, v-if与v-show的区别

vue如何简单的实现弹框,遮罩,点击其他区域关闭弹框, 简单的思路是以一个div作为遮罩, 控制其的v-if(v-show)即可, 掌握到技巧既可以任意扩展

v-if 是直接删除dom节点, 就是这个div就不存在了
v-show 是控制dom的css样式设置为 display: none; 来实现,dom还是存在;

实现如下

maskshow来控制控制遮罩的显示隐藏,绑定一个时间点击遮罩的时候关闭它

<div class="mask" v-show="maskShow" @click="setMaskShow"></div>

有一个弹框它的显示和遮罩一样,里面有个关闭按钮也可以关闭弹框,函数里只需要将maskShow值取反即可

<div class="child" v-show="maskShow">
	<button @click="setMaskShow">关闭</button>
</div>
其他方法

点击时候触发该方法, 判断点的区域

hidePanel(event) {
    let dom = document.getElementById("child");
    if (dom) {
        if (!dom.contains(event.target)) {
        //这句是说如果我们点击到了id为child以外的区域
            this.maskShow = false;
        }
    }
}

全部代码如下

<template>
    <div class="father">
        <div class="mask" v-show="maskShow" @click="setMaskShow"></div>
        <div class="child" id="child" v-show="maskShow">
            <button @click="setMaskShow">关闭</button>
        </div>
        <button @click="setMaskShow">click</button>
    </div>
</template>

<script>
export default {
    data: function(){
        return {
            maskShow: false,
        }
    },
    methods: {
        setMaskShow(){
            this.maskShow = !this.maskShow;
        }
    }
}
</script>

<style>
.father{
    width: 100%;
    height: 100%;
}
.mask{
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: #000;
    opacity: 0.3;
}
button{
    width: 100px;
    height: 40px;
    line-height: 40px;
    text-align: center;
}
.child{
    position: fixed;
    width: 400px;
    height: 400px;
    border: 1px solid #ccc;
    text-align: center;
    line-height: 400px;
    top: calc(50% - 200px);
    left: calc(50% - 200px);
    background: #fff;
}
</style>

猜你喜欢

转载自blog.csdn.net/qq_41916815/article/details/82896513