Skip to content

Instantly share code, notes, and snippets.

@artlili
Created May 15, 2019 20:20
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 artlili/d4bf83e9e4c90983593ff99fddbc956d to your computer and use it in GitHub Desktop.
Save artlili/d4bf83e9e4c90983593ff99fddbc956d to your computer and use it in GitHub Desktop.
click outside
Vue.directive('click-outside', {
bind () {
this.event = event => this.vm.$emit(this.expression, event)
this.el.addEventListener('click', this.stopProp)
document.body.addEventListener('click', this.event)
},
unbind() {
this.el.removeEventListener('click', this.stopProp)
document.body.removeEventListener('click', this.event)
},
stopProp(event) { event.stopPropagation() }
})
Usage:
<div v-click-outside="nameOfCustomEventToCall">
Some content
</div>
In the component:
events: {
nameOfCustomEventToCall: function (event) {
// do something - probably hide the dropdown menu / modal etc.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment