vue3点击空白区域隐藏div
需求是
在主界面中点击按钮,显示组件,点击组件里面的内容时,组件不会隐藏。
但是点击组件外的区域时,组件会进行隐藏
主要内容
一个主界面,我写在了app.vue里面
一个组件,我写在了/src/components/newmodule.vue里面
显隐状态用的时store管理,路径是/src/store/index.ts事先需要安装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尝试一下
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论