标签:handler -o date ESS return att import port opened
vue:解决点击元素之外的地方隐藏该元素
解决方案两个 1:将该div覆盖全屏,给div绑定方法。隐藏
2:elementui clickoutside.js
大至思路 dom监听mouseup 跟 mousedown 目标元素于所有比较。
代码部分:
//dom.js import Vue from ‘vue‘ const isServer = Vue.prototype.$isServer; export const on = (function() { if (!isServer && document.addEventListener) { return function(element, event, handler) { if (element && event && handler) { element.addEventListener(event, handler, false); } }; } else { return function(element, event, handler) { if (element && event && handler) { element.attachEvent(‘on‘ + event, handler); } }; } })();
//clickoutside.js import Vue from ‘vue‘; import { on } from ‘./dom‘; const nodeList = []; const ctx = ‘@@clickoutsideContext‘; let startClick; let seed = 0; !Vue.prototype.$isServer && on(document, ‘mousedown‘, e => (startClick = e)); !Vue.prototype.$isServer && 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]; } };
//main.js 自定义vue 指令 import clickOutside from ‘./assets/js/clickoutside‘ new Vue({ el: ‘#app‘, router, components: { App }, template: ‘<App/>‘ }) Vue.directive(‘clickOutside‘, clickOutside)
//调用 <div v-click-outside="hide" @click="toggle">Toggle</div> <div v-show="opened">Popup item</div>
标签:handler -o date ESS return att import port opened
原文地址:https://www.cnblogs.com/tutao1995/p/12161827.html