Detect click outside element. Can be solved nicely by setting up a custom directive once:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
1 2 3 | <div v-click-outside="nameOfCustomEventToCall"> Some content </div> |
In the component:
1 2 3 4 5 | events: { nameOfCustomEventToCall: function (event) { // do something - probably hide the dropdown menu / modal etc. } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.