There's a few packages that solve this:
Feb 21, 2018
9
Level 1
Close dropdown when click another element
I have a few dropdown menus that I want to close by clicking outside, another element or focusing an input field.
I'm using this kind of code
<a @click="dropdown()"></a>
dropdown() {
this.openDropdown = !this.openDropdown;
}
Level 35
update: see ellisio's answer for a cleaner solution
If you do not want to add one of the packages mentioned above. You could also try this example (not mine) https://jsfiddle.net/kym2rvyL/1/ it is actually doing the same as one of the packages shown above but it is an easy copy paste:
Your Vue component could look like:
created: function() {
let self = this;
window.addEventListener('click', function(e){
// close dropdown when clicked outside
if (!self.$el.contains(e.target)){
self.dropDropdown = false
}
})
}
7 likes
Please or to participate in this conversation.