Home > Net >  How can i make a dropdown menu close when i open another one in Vuejs 3 (without plugins)
How can i make a dropdown menu close when i open another one in Vuejs 3 (without plugins)

Time:10-05

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 >
    <li v-for="menu in menus" :key="menu.id">
        <button  @click="toggle">
            {{menu.name}}
            <ion-icon name="chevron-down-outline"></ion-icon>
        </button>
        <div  v-show="open">
            <router-link to="/" v-for="item in menu.subMenu">
                <div >
                    {{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;
        }
    }
}

CodePudding user response:

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 >
    <li v-for="menu in menus" :key="menu.id">
      <button  @click="toggle(menu.id)">
        {{ menu.name }}
        <ion-icon name="chevron-down-outline"></ion-icon>
      </button>
      <div  v-show="menu.id === open">
        <div to="/" v-for="item in menu.subMenu">
          <div >
            {{ item }}
          </div>
        </div>
      </div>
    </li>
  </ul>
</div>

  • Related