Issue
I have two dropdowns menu in a component and i want to close one when the other is open I'm new to Vuejs so i dont want to use any plugin, i want to build it from scratch, if anyone could help me with this ? here's my actual code
<template>
<ul class="menu">
<li v-for="menu in menus" :key="menu.id">
<button class="button is-white" @click="toggle">
{{menu.name}}
<ion-icon name="chevron-down-outline"></ion-icon>
</button>
<div class="dropdown" v-show="open">
<router-link to="/" v-for="item in menu.subMenu">
<div class="options">
{{item}}
</div>
</router-link>
</div>
</li>
</ul>
data() {
return {
open: false,
menus: [
{
id: 1,
name: 'My Profile',
subMenu: ['Dashboard', 'My Profile', 'Logout']
},
{
id: 2,
name: ' My Orders',
subMenu: ['Order']
}
],
}
},
created() {
window.addEventListener("click", this.close);
},
beforeDestroy() {
window.removeEventListener("click", this.close);
},
methods: {
toggle() {
this.open = !this.open
},
close(e) {
if (!this.$el.contains(e.target)) {
this.open = false;
}
}
}
Solution
Use id instead of boolean for open/close:
const app = Vue.createApp({
data() {
return {
open: null,
menus: [{id: 1, name: 'My Profile', subMenu: ['Dashboard', 'My Profile', 'Logout']}, {id: 2, name: ' My Orders', subMenu: ['Order']}],
}
},
methods: {
toggle(id) {
this.open = this.open === id ? null : id
},
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<ul class="menu">
<li v-for="menu in menus" :key="menu.id">
<button class="button is-white" @click="toggle(menu.id)">
{{ menu.name }}
<ion-icon name="chevron-down-outline"></ion-icon>
</button>
<div class="dropdown" v-show="menu.id === open">
<div to="/" v-for="item in menu.subMenu">
<div class="options">
{{ item }}
</div>
</div>
</div>
</li>
</ul>
</div>
Answered By - Nikola Pavicevic Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.