I am looking to implement multiple dropdowns in a single component, using one variable to control their display and also have them close when clicking away from the dropdown. Here is my code snippet:
<div class="dropdown">
<button @click.prevent="isOpen = !isOpen"></button>
<div v-show="isOpen">Content</div>
</div>
// Second dropdown within the same component
<div class="dropdown">
<button @click.prevent="isOpen = !isOpen"></button>
<div v-show="isOpen">Content</div>
</div>
data() {
return {
isOpen: false
}
},
watch: {
isOpen(isOpen) {
if(isOpen) {
document.addEventListener('click', this.closeIfClickedOutside)
}
}
},
methods: {
closeIfClickedOutside(event){
if(! event.target.closest('.dropdown')){
this.isOpen = false;
}
}
}
However, I am encountering an issue where clicking on one dropdown menu displays both of them. As a newcomer to Vue, I am struggling to find a solution to this problem.