Skip to content

Instantly share code, notes, and snippets.

@almino
Created May 26, 2017 17:48
Show Gist options
  • Save almino/435abf4b203571cba4c8ca1884997f9c to your computer and use it in GitHub Desktop.
Save almino/435abf4b203571cba4c8ca1884997f9c to your computer and use it in GitHub Desktop.
Directive `v-click-outside`
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
}
}
}
}
@ogomaemmanuel
Copy link

This works well but when I try to work with it inside Bootsrap vue Modal It does not work. Can it be made to work inside bootstrap vue modal

@mariobalca
Copy link

mariobalca commented Dec 10, 2018

This works well but when I try to work with it inside Bootsrap vue Modal It does not work. Can it be made to work inside bootstrap vue modal

I'm having the exact same problem, how could we fix this?

@gilsoro
Copy link

gilsoro commented Apr 20, 2019

@mariobalca
Just change
if (bubble || (!el.contains(e.target) && el !== e.target)) {
to
if (bubble || -1 == e.path.indexOf(el)) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment