场景:el-popover通过visible控制显隐;同时el-popover是遍历生成的多个。
原文档的使用visible后就不能点击其他地方使其隐藏
主要监听全局点击事件即可
<template><div><template v-for="(item,index) in arr" :key="index"><el-popover :visible="visible === item" placement="bottom" title="标题可去除" :width="200"content="this is content, this is content, this is content"><template #reference><el-button class="m-2" @click.stop="visible = item">遍历多个{{item}}</el-button></template><div @click.stop="()=>{}"><span>自定义内容{{item}} <br> 禁止冒泡 避免点击隐藏情况</span></div></el-popover></template><div class="content">这是页面的其他内容</div></div>
</template><script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';let visible = ref(undefined)
let arr = ref([111, 222, 333, 444])
const handleDivClick = () => {console.log('点击本身'); // 点击特定 div 时打印
};const handleClickOutside = () => {console.log('点击其他元素'); // 点击其他元素时打印visible.value = undefined
};// 在组件挂载时添加全局点击事件监听器
onMounted(() => {window.addEventListener('click', handleClickOutside);
});// 在组件卸载时移除全局点击事件监听器
onBeforeUnmount(() => {window.removeEventListener('click', handleClickOutside);
});
</script><style>
.button {padding: 10px;background-color: #007bff;color: white;text-align: center;cursor: pointer;margin-bottom: 10px;
}.content {padding: 20px;border: 1px solid #ccc;
}
</style>