typescript
import type { DirectiveBinding } from "vue";
export default {
bind(el: HTMLElement, binding: DirectiveBinding<Function>) {
//声明一个给document绑定的事件
function documentClick(event: Event) {
const target = event.target as unknown as Node;
if (el.contains(target)) {
return false;
}
//如果绑定了关闭函数就触发
if (binding.expression) {
binding.value(event);
}
}
// 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
el["__clickOutside__"] = documentClick;
document.addEventListener("click", documentClick);
},
unbind(el: HTMLElement) {
// 解除事件监听
document.removeEventListener("click", el["__clickOutside__"]);
Reflect.deleteProperty(el, "__clickOutside__");
},
};
使用
import Vue from "vue";
import clickOutside from "@/directives/clickOutside";
Vue.directive("clickOutside", ClickOutside);
<template>
<div class="menu-wrap" v-clickOutside="Close">
...
</div>
</template>