vue事件监听关闭弹窗
<button @click="showCart = true">打开购物车</button>
<div class="my-float-cart" ref="myDiv" v-show="showCart">
购物车内容这里忽略代码
</div>
// 监听showCart
watch: {
'showCart': function (v) {
let _this = this
if (v) {
// alert(this.showCart)
setTimeout(function () { // 防止时间差
document.addEventListener('click', _this.listener)
}, 50)
} else {
document.removeEventListener('click', this.listener)
}
}
}
// 监听事件
methods:{
listener (event) {
const e = event || window.event
if (this.$refs.myDiv && !this.$refs.myDiv.contains(e.target)) {
this.showCart = false // 点击目标myDiv以外的地方关闭ref="myDiv"这个弹窗
}
}
}
如果对应的refs.myDiv是数组【即<div class="my-float-cart" ref="myDiv"
是循环遍历出来】则listener改为,至于showCart如何对应多个<div class="my-float-cart" ref="myDiv" v-if="【使用遍历的index控制】 showIndex === index">
// 监听事件
listener (event) { // 合同相关
const e = event || window.event
if (this.$refs['myDiv'] && this.testEvent(this.$refs['myDiv'], e)) {
this.showIndex= -1
}
},
// 过滤对应出当前监听的弹窗
testEvent (arr, e) {
let result = false
if (Array.isArray(arr)) {
arr.forEach(v => {
if (!v.contains(e.target)) {
result = true
}
})
} else {
result = !arr.contains(e.target)
}
return result
}
data数据:
data: () {
return: {
showIndex: -1
}
}
打开的button:
<button @click="showIndex = index">打开购物车</button>