vue3實(shí)現(xiàn)點(diǎn)擊空白區(qū)域隱藏div
vue3點(diǎn)擊空白區(qū)域隱藏div
需求是
在主界面中點(diǎn)擊按鈕,顯示組件,點(diǎn)擊組件里面的內(nèi)容時(shí),組件不會(huì)隱藏。
但是點(diǎn)擊組件外的區(qū)域時(shí),組件會(huì)進(jìn)行隱藏
主要內(nèi)容
一個(gè)主界面,我寫在了App.vue里面
一個(gè)組件,我寫在了/src/components/NewModule.vue里面
顯隱狀態(tài)用的時(shí)store管理,路徑是/src/store/index.ts事先需要安裝pinia,不熟悉pinia的可以先看一下pinia簡(jiǎn)單使用
- App.vue
<template>
<!-- 主界面容器,按鈕點(diǎn)擊顯示組件,引入組件 -->
<el-button type="primary" @click="showBox">點(diǎn)擊顯示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結(jié)構(gòu)化
const store = useUsersStore()
const codeDom = ref()
const { isHide } = storeToRefs(store)
//監(jiān)聽點(diǎn)擊事件,改變組件的顯隱狀態(tài)
const closeSelect = () => {
document.addEventListener('click', (e) => {
if (codeDom.value && !codeDom.value.contains(e.target)) {
store.changeState(false)
}
})
}
//監(jiān)聽store狀態(tài)的改變,若狀態(tài)為true時(shí),運(yùn)行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: {},
})總結(jié)
ok,完結(jié),感興趣的可以做個(gè)demo嘗試一下
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue 路由跳轉(zhuǎn)四種方式實(shí)踐案例 (帶參數(shù))
本文詳細(xì)介紹了Vue中通過$router對(duì)象實(shí)現(xiàn)的四種路由跳轉(zhuǎn)方法:router-link的使用、this.$router.push()和this.$router.replace(),以及參數(shù)傳遞的query與params區(qū)別,感興趣的朋友跟隨小編一起看看吧2025-05-05
關(guān)于Uncaught(in?promise)TypeError:?list?is?not?iterable報(bào)錯(cuò)
這篇文章主要給大家介紹了關(guān)于Uncaught(in?promise)TypeError:?list?is?not?iterable報(bào)錯(cuò)的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
詳解使用Vue.Js結(jié)合Jquery Ajax加載數(shù)據(jù)的兩種方式
本篇文章主要介紹了詳解使用Vue.Js結(jié)合Jquery Ajax加載數(shù)據(jù)的兩種方式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-01-01
Vue中使用this.$set()如何新增數(shù)據(jù),更新視圖
這篇文章主要介紹了Vue中使用this.$set()實(shí)現(xiàn)新增數(shù)據(jù),更新視圖方式。具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
Vue組件之間的參數(shù)傳遞與方法調(diào)用的實(shí)例詳解
這篇文章主要介紹了Vue組件之間的參數(shù)傳遞與方法調(diào)用,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-12-12

