在util文件夹下生成clickoutside.js
let cache = {}; let key = 1; export default { inserted(el, binding) { el.outsideKey = key++; const self = {}; self.documentHandler = (e) => { if (el.contains(e.target)) { return false; } if (binding.value) { binding.value(e); } return true; }; cache[el.outsideKey] = self; document.addEventListener('click', self.documentHandler); }, unbind(el) { const self = cache[el.outsideKey]; document.removeEventListener('click', self.documentHandler); delete cache[el.outsideKey]; }, };
复制
使用clickoutside
<template> <div v-clickoutside="onClickOutside"></div> </template> <script> import Clickoutside from "@/util/clickoutside"; export default { directives: { Clickoutside }, methods: { onClickOutside() { // ... } } } </script>
复制
vue3的使用方法参考Vue3 自定义指令:ClickOutside(点击当前区域之外的位置)-CSDN博客