From ce4235e88864d7d4a19667df30d898c72c00609e Mon Sep 17 00:00:00 2001 From: jmal Date: Wed, 31 Mar 2021 18:03:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=EF=BC=9A=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E4=B8=80=E4=BA=9B=E7=BB=86=E8=8A=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/directives.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/utils/directives.js b/src/utils/directives.js index ca2a85e..2f56bf8 100644 --- a/src/utils/directives.js +++ b/src/utils/directives.js @@ -258,3 +258,28 @@ Vue.directive('dialogDragWidth', { } }) +// 除某元素外的点击事件 +Vue.directive('clickoutside', { // 初始化指令 + bind(el, binding, vnode) { + function documentHandler(e) { + // 这里判断点击的元素是否是本身,是本身,则返回 + if (el.contains(e.target)) { + return false; + } + // 判断指令中是否绑定了函数 + if (binding.expression) { + // 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法 + binding.value(e); + } + } + // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听 + el.__vueClickOutside__ = documentHandler; + document.addEventListener('click', documentHandler); + }, + update() {}, + unbind(el, binding) { // 解除事件监听 + document.removeEventListener('click', el.__vueClickOutside__); + delete el.__vueClickOutside__; + } +}) +