vue3 click on the blank area to hide div
The requirement is
Click the button in the main interface to display the component. When clicking on the contents inside the component, the component will not be hidden.
However, when clicking on an area outside the component, the component will hide
Main content
I wrote a main interface in it
A component I wrote in /src/components/
When using the store management in the visible and hidden state, the path is /src/store/pinia needs to be installed in advance. If you are not familiar with pinia, you can take a look first.pinia is simple to use
<template> <!-- Main interface container,Click button to display component,Introducing components --> <el-button type="primary" @click="showBox">Click to displaybox</el-button> <div style="width: 100%;height: 100%; background-color: aquamarine;"> <NewModel></NewModel> </div> </template> <script setup lang="ts"> import NewModel from '@/components/' //Introduce componentsimport { useUsersStore } from '@/store/index' const store = useUsersStore() const showBox = (e: any) => { (true) () //Stop the incident from bubbles, it is important to *, it is very important} </script> <style></style>
<template> <!-- Subcomponent container --> <div ref="codeDom" style="width: 300px; height: 300px; background-color: antiquewhite;" v-if=""></div> </template> <script lang='ts' setup> import { watch, ref, onUnmounted } from 'vue' import { useUsersStore } from '@/store/index' //Introduce storeimport { storeToRefs } from 'pinia'; //pinia structureconst store = useUsersStore() const codeDom = ref() const { isHide } = storeToRefs(store) // Listen to click events and change the visible and hidden state of the componentconst closeSelect = () => { ('click', (e) => { if ( && !()) { (false) } }) } // Listen to the change of the store state. If the state is true, run closeSelectwatch(isHide, (val) => { if (val) { closeSelect() } }) onUnmounted(() => { ('click', closeSelect) }) </script> <style lang='scss' scoped></style>
- Store
import { defineStore } from 'pinia' export const useUsersStore = defineStore('users', { state: () => { return { isHide: false, }; }, actions: { changeState(val) { = val }, }, getters: {}, })
Summarize
OK, it's over. If you are interested, you can try it out.
The above is personal experience. I hope you can give you a reference and I hope you can support me more.