I'm using Vue.js, I don't think it matters what lib I'm using though, just one that allows you to have web components. Anyway - I have a dropdown component (see code below), and I need to know, how do I close the dropdown on body click? If it is a component that has its own scoped data, I'm assuming you can't just add an event listener to the body, it's out of scope, right? How would I go about this?
dropdown.template.html
<li class="dropdown">
<a href="#" tabindex="1" v-on="click: toggleDropdown($event), keydown: closeDropdown($event) | key 'esc'"><content select=".dropdown__button"></content></a>
</li>
<ul class="dropdown__menu" v-show="displayed">
<content select=".menu"></content>
</ul>
dropdown.js
module.exports = {
template: require('../views/dropdown.template.html'),
data: function() {
return {
displayed: false
};
},
methods: {
toggleDropdown: function(e) {
e.preventDefault();
this.displayed = !this.displayed;
},
closeDropdown: function(e) {
e.preventDefault();
e.stopPropagation();
this.displayed = false;
}
}
}
You should add the blur
event:
<a href="#" tabindex="1" v-on="click: toggleDropdown($event), keydown: closeDropdown($event) | key 'esc', blur: closeDropdown($event)"><content select=".dropdown__button"></content></a>