【Vue】点击组件外部隐藏组件自身

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w390058785/article/details/83380166

前言:在开发组件的时候,点击组件外部隐藏组件自身的这种情况很长见到,例如:时间选择框组件,下拉选择框组件等等。

一、直接上代码

<!-- 示例组件 -->

<template>
    <div class="index" @click.stop>
        <button @click="isShow = !isShow ">{{ isShow ? '关闭':'打开' }}弹窗</button>
        <div class="content" v-show="isShow"></div>
    </div>
</template>

<script>
export default {
    data() {
        return {
           isShow:false
        }
    },
    mounted(){
        document.body.addEventListener('click',()=>{
            this.isShow = false;
        },false);
    }
}
</script>

<style>
    .index { width:200px; }
    .content { 
        margin-top:10px; 
        width:200px; 
        height:200px; 
        background:#ccc; 
    }
</style>

像这样就可以实现点击组件外部隐藏组件自身

其中重要的两点就是:

1、最外层div中添加一个@click.stop(取消事件冒泡),可以不添加事件名。

2、在mounted给body添加一个点击事件,事件触发组件的隐藏。

猜你喜欢

转载自blog.csdn.net/w390058785/article/details/83380166
今日推荐