vue3实现点击空白区域隐藏div
作者:bangbang给你两锤
这篇文章主要介绍了vue3实现点击空白区域隐藏div方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue3点击空白区域隐藏div
需求是
在主界面中点击按钮,显示组件,点击组件里面的内容时,组件不会隐藏。
但是点击组件外的区域时,组件会进行隐藏
主要内容
一个主界面,我写在了App.vue里面
一个组件,我写在了/src/components/NewModule.vue里面
显隐状态用的时store管理,路径是/src/store/index.ts事先需要安装pinia,不熟悉pinia的可以先看一下pinia简单使用
- App.vue
<template>
<!-- 主界面容器,按钮点击显示组件,引入组件 -->
<el-button type="primary" @click="showBox">点击显示box</el-button>
<div style="width: 100%;height: 100%; background-color: aquamarine;">
<NewModel></NewModel>
</div>
</template>
<script setup lang="ts">
import NewModel from '@/components/NewModel.vue' //引入组件
import { useUsersStore } from '@/store/index'
const store = useUsersStore()
const showBox = (e: any) => {
store.changeState(true)
e.stopPropagation() //阻止事件冒泡,必须要*,很重要
}
</script>
<style></style>- NewModel.vue
<template>
<!-- 子组件容器 -->
<div ref="codeDom" style="width: 300px; height: 300px; background-color: antiquewhite;" v-if="store.isHide"></div>
</template>
<script lang='ts' setup>
import { watch, ref, onUnmounted } from 'vue'
import { useUsersStore } from '@/store/index' //引入store
import { storeToRefs } from 'pinia'; //pinia结构化
const store = useUsersStore()
const codeDom = ref()
const { isHide } = storeToRefs(store)
//监听点击事件,改变组件的显隐状态
const closeSelect = () => {
document.addEventListener('click', (e) => {
if (codeDom.value && !codeDom.value.contains(e.target)) {
store.changeState(false)
}
})
}
//监听store状态的改变,若状态为true时,运行closeSelect
watch(isHide, (val) => {
if (val) {
closeSelect()
}
})
onUnmounted(() => {
document.removeEventListener('click', closeSelect)
})
</script>
<style lang='scss' scoped></style>- store的index.ts
import { defineStore } from 'pinia'
export const useUsersStore = defineStore('users', {
state: () => {
return {
isHide: false,
};
},
actions: {
changeState(val) {
this.isHide = val
},
},
getters: {},
})总结
ok,完结,感兴趣的可以做个demo尝试一下
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
