Created
May 26, 2017 17:48
-
-
Save almino/435abf4b203571cba4c8ca1884997f9c to your computer and use it in GitHub Desktop.
Directive `v-click-outside`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default { | |
directives: { | |
/* | |
* http://stackoverflow.com/questions/43693665/vuejs-editable-close-when-click-outside-in-vuejs | |
* https://jsfiddle.net/Linusborg/Lx49LaL8/ | |
*/ | |
'click-outside': { | |
bind: function (el, binding, vNode) { | |
// Provided expression must evaluate to a function. | |
if (typeof binding.value !== 'function') { | |
const compName = vNode.context.name | |
let warn = `[Vue-click-outside:] provided expression '${binding.expression}' is not a function, but has to be` | |
if (compName) { | |
warn += ` Found in component '${compName}'` | |
} | |
console.warn(warn) | |
} | |
// Define Handler and cache it on the element | |
const bubble = binding.modifiers.bubble | |
const handler = (e) => { | |
if (bubble || (!el.contains(e.target) && el !== e.target)) { | |
binding.value(e) | |
} | |
} | |
el.__vueClickOutside__ = handler | |
// add Event Listeners | |
document.addEventListener('click', handler) | |
}, | |
unbind: function (el, binding) { | |
// Remove Event Listeners | |
document.removeEventListener('click', el.__vueClickOutside__) | |
el.__vueClickOutside__ = null | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mariobalca
Just change
if (bubble || (!el.contains(e.target) && el !== e.target)) {
to
if (bubble || -1 == e.path.indexOf(el)) {