Vue 自定义指令:ClickOutside(点击当前区域之外的位置)
在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博客
原文地址:https://blog.csdn.net/qq_29715077/article/details/136910139
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!