<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://lib.baomitu.com/vue/2.6.12/vue.min.js"></script>
<style>
#box {
position: fixed;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
background-color: #00a0d4;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="app">
<div ref="container">
<h1>{{flag}}</h1>
<button @click="flag = true" v-show="!flag">boxShow</button>
<div id="box" v-show="flag">弹框</div>
</div>
</div>
<script>
export default {
name:'cxk'
data: {
flag: false
},
mounted() {
window.addEventListener('click', this.otherClose)
},
beforeDestroy() {
/* 组件销毁的时候要移除侦听器 */
window.removeEventListener('click', this.otherClose)
},
methods: {
otherClose(e) {
if (!this.$refs.container.contains(e.target)) this.flag = false
}
}
}
</script>
</body>
</html>
Vue 点击其他地方关闭弹窗
最新推荐文章于 2024-05-09 09:30:26 发布