<template><div><div v-click-outside="onClickOutside" class="box">点击内容外区域会触发事件</div></div>
</template><script setup>
const vClickOutside = {mounted(el, binding) {function eventHandler(e) {if (el.contains(e.target)) {return false}if (binding.value && typeof binding.value === "function") {binding.value(e)}}el.__click_outside__ = eventHandlerdocument.addEventListener("click", eventHandler)},beforeUnmount(el) {document.removeEventListener("click", el.__click_outside__)delete el.__click_outside__},
}
const onClickOutside = () => {console.log("点击了外部 DOM")
}
</script><style scoped>
.box {width: 200px;height: 200px;background-color: lightblue;text-align: center;line-height: 200px;
}
</style>