提供两种常用方法
1、方法比较简单,原理是需要隐藏的点击document使其show的值为false,
点击需要出现的加上阻止冒泡即可。@click.stop="isShow"
mounted(){
var that=this;//this的指向问题
document.addEventListener('click',function(e){
that.show=false; //这里that代表组件,this代表document
})
},
methods{
isShow:function(){
this.show=true
}
}
2、将点击的区域过滤。不需要再阻止冒泡,需要使用到ref属性
<template>
<div ref="box">
<div @click="isShow"></div>
</div>
</template>
mounted(){
let that=this;
document.addEventListener('click',function(e){
if(!that.$refs.box.contains(e.target)){
that.show = false;
}
})
},
methods:{
isShow:function(){
this.show=true
}
}