这篇文章主要讲解了“elementui中的clickoutside点击空白隐藏元素怎么实现”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“elementui中的clickoutside点击空白隐藏元素怎么实现”吧!
基本使用
点击div,closeBox方法不会执行,点击空白才执行
<template>
<div class="app">
<div v-show="isShowBox" v-clickoutside="closeBox" class="box"></div>
</div>
</template>
<script>
import Clickoutside from 'element-ui/src/utils/clickoutside'
export default {
directives: {
Clickoutside
},
data() {
return {
isShowBox: true
}
},
methods: {
closeBox() {
this.isShowBox = false;
}
}
};
源码实现
在document元素上注册'mousedown'和'mouseup'事件,mouseup时会执行使用了该指令元素上的documentHandler方法
documentHandler方法里判断点击的元素是否为使用了指令的元素,不是就执行closeBox的方法
import Vue from 'vue';
import { on } from 'element-ui/src/utils/dom';
const nodeList = [];
const ctx = '@@clickoutsideContext';
let startClick;
let seed = 0;
on(document, 'mousedown', e => (startClick = e));
on(document, 'mouseup', e => {
nodeList.forEach(node => node[ctx].documentHandler(e, startClick));
});
function createDocumentHandler(el, binding, vnode) {
return function(mouseup = {}, mousedown = {}) {
if (!vnode ||
!vnode.context ||
!mouseup.target ||
!mousedown.target ||
el.contains(mouseup.target) ||
el.contains(mousedown.target) ||
el === mouseup.target ||
(vnode.context.popperElm &&
(vnode.context.popperElm.contains(mouseup.target) ||
vnode.context.popperElm.contains(mousedown.target)))) return;
if (binding.expression &&
el[ctx].methodName &&
vnode.context[el[ctx].methodName]) {
vnode.context[el[ctx].methodName]();
} else {
el[ctx].bindingFn && el[ctx].bindingFn();
}
};
}
/**
* v-clickoutside
* @desc 点击元素外面才会触发的事件
* @example
* ```vue
* <div v-element-clickoutside="handleClose">
* ```
*/
export default {
bind(el, binding, vnode) {
nodeList.push(el);
const id = seed++;
el[ctx] = {
id,
documentHandler: createDocumentHandler(el, binding, vnode),
methodName: binding.expression,
bindingFn: binding.value
};
},
update(el, binding, vnode) {
el[ctx].documentHandler = createDocumentHandler(el, binding, vnode);
el[ctx].methodName = binding.expression;
el[ctx].bindingFn = binding.value;
},
unbind(el) {
let len = nodeList.length;
for (let i = 0; i < len; i++) {
if (nodeList[i][ctx].id === el[ctx].id) {
nodeList.splice(i, 1);
break;
}
}
delete el[ctx];
}
};
以上就是elementui中的clickoutside点击空白隐藏元素怎么实现的详细内容,更多关于elementui中的clickoutside点击空白隐藏元素怎么实现的资料请关注九品源码其它相关文章!