代码实现:
vue2
<template>
<div>
<span v-show="isShow" ref="showPanel">需要隐藏或显示的文本</span>
<button @click.stop="isShow = true">显示</button>
</div>
</template>
<script>
export default {
data () {
return {
isShow:false,
}
},
created(){
document.addEventListener('click',(e)=>{
if(this.$refs.showPanel){
let isSelf = this.$refs.showPanel.contains(e.target)
if(!isSelf){
this.isShow = false
}
}
})
}
}
</script>
vue3:
<script setup>
import {ref} from "vue";
const isShow = ref(false)
const showPanel = ref(null)
document.addEventListener('click',(e)=>{
if(showPanel.value){
let isSelf = showPanel.value.contains(e.target)
if(!isSelf){
isShow.value = false
}
}
})
</script>
<template>
<div>
<span v-show="isShow" ref="showPanel">需要隐藏或显示的文本</span>
<button @click.stop="isShow = true">显示</button>
</div>
</template>
<style scoped>
</style>