vue3實現(xiàn)點擊空白區(qū)域隱藏div
vue3點擊空白區(qū)域隱藏div
需求是
在主界面中點擊按鈕,顯示組件,點擊組件里面的內(nèi)容時,組件不會隱藏。
但是點擊組件外的區(qū)域時,組件會進行隱藏
主要內(nèi)容
一個主界面,我寫在了App.vue里面
一個組件,我寫在了/src/components/NewModule.vue里面
顯隱狀態(tài)用的時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結(jié)構(gòu)化
const store = useUsersStore()
const codeDom = ref()
const { isHide } = storeToRefs(store)
//監(jiā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時,運行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é),感興趣的可以做個demo嘗試一下
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue中圖片轉(zhuǎn)base64格式實現(xiàn)方法
這篇文章主要介紹了vue中圖片轉(zhuǎn)base64格式實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08
vue3中使用viewerjs實現(xiàn)圖片預覽效果的項目實踐
viewer.js是一款開源的圖片預覽插件,功能十分強大,本文主要介紹了vue3中使用viewerjs實現(xiàn)圖片預覽效果的項目實踐,具有一定的參考價值,感興趣的可以了解一下2023-09-09
vue實現(xiàn)將一個數(shù)組內(nèi)的相同數(shù)據(jù)進行合并
今天小編就為大家分享一篇vue實現(xiàn)將一個數(shù)組內(nèi)的相同數(shù)據(jù)進行合并,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11

