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)base64格式實(shí)現(xiàn)方法
這篇文章主要介紹了vue中圖片轉(zhuǎn)base64格式實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08vue3中使用viewerjs實(shí)現(xiàn)圖片預(yù)覽效果的項(xiàng)目實(shí)踐
viewer.js是一款開源的圖片預(yù)覽插件,功能十分強(qiáng)大,本文主要介紹了vue3中使用viewerjs實(shí)現(xiàn)圖片預(yù)覽效果的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09vue實(shí)現(xiàn)將一個(gè)數(shù)組內(nèi)的相同數(shù)據(jù)進(jìn)行合并
今天小編就為大家分享一篇vue實(shí)現(xiàn)將一個(gè)數(shù)組內(nèi)的相同數(shù)據(jù)進(jìn)行合并,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11Vue實(shí)現(xiàn)注冊(cè)頁面的用戶交互詳解
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)注冊(cè)頁面的用戶交互的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),對(duì)我們深入掌握vue有一定的幫助,需要的小伙伴可以參考下2023-12-12