在Vue中点击某个元素以外的元素时让这个元素隐藏或关闭

在Vue中点击某个元素以外的元素时让这个元素隐藏或关闭

在实际开发中,可能会有点击某个元素以外的元素时让这个元素隐藏或关闭的需求。在Vue中实现则更加简单。

思路

为全局document添加click事件,判断是否为指定节点及其子节点,如果不是则隐藏该指定节点。

例如该组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div>
<span v-show="isShow">没点击我我就消失了哦</span>
<button @click="isShow = true">显示</button>
</div>
</template>

<script>
export default {
data () {
return {
isShow:false,
}
}
</script>

当前组件现有功能是:span默认不显示,当点击button时显示span

而现在想要的功能是,当点击button时显示span,当点击spanbutton以外的节点都导致span隐藏。

实现

为span加上ref 以便于获取该DOM节点

1
<span v-show="isShow" ref="showPanel">没点击我我就消失了哦</span>

当前组件添加created hook

  • 为所有document添加click事件句柄
  • 判断当前的spanthis.$refs.showPanel)是否存在
  • 判断当前点击的元素(e.target)是否被span所包含
  • 若不包含则导致span隐藏
1
2
3
4
5
6
7
8
9
10
created(){
document.addEventListener('click',(e)=>{
if(this.$refs.showPanel){
let isSelf = this.$refs.showPanel.contains(e.target)
if(!isSelf){
this.isShow = false
}
}
})
}

改进

实时上述工作完成后,还存在一个问题就是当点击button时导致isShow最终又变为false(事件冒泡,button也是span之外的元素)。所以为了防止冒泡,需要为buttonclick事件添加.stop修饰符

1
<button @click.stop="isShow = true">显示</button>
0%