需求: 点击某元素可以关闭打开弹出框,点击弹出框外可以关闭弹出框,点击框内不处理
// 点击此元素可以显示或者隐藏弹出框
<div @click="showInfo" class="z-nodeal">
...
</div>
// 弹出框 点击类名为'z-nodeal'之外的元素才会触发指令绑定函数
<div class="boxinfo" v-show="active1">
<div v-clickoutside:['z-nodeal']='closeIconBlock' >
</div>
</div>
methods: {
showInfo() {
this.active1 = !this.active1;
},
closeIconBlock() {
if (this.active1) {
this.active1 = false;
}
},
},
// 注册自定义指令
directives: { clickoutside },
// 自定义指令函数
const clickoutside = {
bind(el, binding) {
function handler(e) {
if (el.contains(e.target) || e.target.className.includes(binding.arg)) {
return false;
}
if (binding.expression) {
binding.value(e);
}
}
el._zClickOutside = handler;
document.addEventListener('click', handler);
},
unbind(el) {
// 解除事件监听
document.removeEventListener('click', el._zClickOutside);
delete el._zClickOutside;
}
};