前言
在 Vue 开发中,使用自定义组件或者第三方ui组件经常会遇到需要实现点击弹窗以外区域关闭弹窗的需求。下边是一个小demo
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、实现思路
1,在 Vue 组件中,使用v-if或v-show指令创建弹窗或使用UI组件库弹窗来控制弹窗的显示和隐藏
2,给整个页面添加一个点击事件监听器,当用户点击页面上除弹窗以外的区域时,关闭弹窗。
3,当用户点击弹窗时,阻止事件冒泡,防止点击弹窗内部区域时误关闭弹窗。
三、代码
<template>
<div>
<button class="my-button" @click="showModal = true">打开弹窗</button>
<div v-if="showModal" class="modal">
<div class="modal-content" @click="handleClick">
<h2>弹窗内容</h2>
<p>这是一个弹窗,可以在这里添加任何内容。</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
showModal: false
};
},
mounted() {
document.addEventListener('click', this.handleOutsideClick);
},
beforeDestroy() {
document.removeEventListener('click', this.handleOutsideClick);
},
methods: {
handleOutsideClick(event) {
// 阻止触发按钮区域的点击事件,否则将打不开弹窗
if (event.target.classList.contains('my-button')) {
return
}
// 打开弹窗并且点击了其他区域,关闭弹窗
if (this.showModal && !event.target.classList.contains('modal-content')) {
this.showModal = false;
}
}
}
};
</script>
<style>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 5px;
}
</style>
,
四、效果
总结
这样一个简单的点击弹窗以外区域关闭弹窗的需求的效果就完成了