Skip to content

Instantly share code, notes, and snippets.

@szkrd
Created August 29, 2016 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szkrd/f73713142fe5360b8ea6a5e7a14adb6b to your computer and use it in GitHub Desktop.
Save szkrd/f73713142fe5360b8ea6a5e7a14adb6b to your computer and use it in GitHub Desktop.
vuejs click outside element directive
export default {
bind() {
let click = this.click = e => {
let target = e.target;
let opacity = parseInt((window.getComputedStyle(this.el, null) || {}).opacity, 10) || 0;
let hidden = this.el.style.display === 'none';
if (opacity === 0 || hidden) {
return;
}
let boundFn = this.vm[this.expression];
let el = target;
let found = el === this.el ? 1 : 0;
let parent;
while (!found) {
parent = el.parentElement;
if (parent === null) { // detached
return;
}
if (parent === this.el) {
found = 1;
} else if (parent === document.body) { // guard
found = 2;
}
el = parent;
}
// not inside and callback is a function
if (found !== 1 && typeof boundFn === 'function') {
let id = target.id || '';
boundFn(id, e);
}
};
document.body.addEventListener('click', click, false);
},
unbind() {
document.body.removeEventListener('click', this.click);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment