当前位置: 代码网 > it编程>前端脚本>Vue.js > vue3实现点击空白区域隐藏div

vue3实现点击空白区域隐藏div

2024年05月26日 Vue.js 我要评论
vue3点击空白区域隐藏div需求是在主界面中点击按钮,显示组件,点击组件里面的内容时,组件不会隐藏。但是点击组件外的区域时,组件会进行隐藏主要内容一个主界面,我写在了app.vue里面一个组件,我写

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尝试一下 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com