How to create a multi-level dropdown menu in Vue.js



Image not found!!

Creating a multi-level dropdown menu in Vue.js involves using Vue components and managing the state of the menu items. Here's a basic example of how you can achieve this:

  1. First, set up your Vue component structure. You'll have a main component for the dropdown menu and sub-components for each dropdown item.

  2. Use Vue's data to manage the state of the menu items and their visibility.

  3. Implement event handling to toggle the visibility of sub-menus.

Here's a basic example:

html
<template> <div class="dropdown"> <div class="dropdown-item" @click="toggleDropdown"> Main Menu <i class="fas fa-chevron-down"></i> </div> <ul v-if="isDropdownOpen" class="sub-menu"> <li class="sub-menu-item" @click="selectItem('Item 1')">Item 1</li> <li class="sub-menu-item" @click="toggleSubmenu(2)">Item 2 <ul v-if="subMenuVisible[2]" class="sub-menu"> <li class="sub-menu-item">Subitem 1</li> <li class="sub-menu-item">Subitem 2</li> </ul> </li> <li class="sub-menu-item" @click="selectItem('Item 3')">Item 3</li> </ul> </div> </template> <script> export default { data() { return { isDropdownOpen: false, selectedItem: null, subMenuVisible: { 2: false } // Keep track of visibility for each sub-menu }; }, methods: { toggleDropdown() { this.isDropdownOpen = !this.isDropdownOpen; }, selectItem(item) { this.selectedItem = item; this.isDropdownOpen = false; }, toggleSubmenu(index) { this.$set(this.subMenuVisible, index, !this.subMenuVisible[index]); } } }; </script> <style scoped> .dropdown { position: relative; display: inline-block; } .dropdown-item { cursor: pointer; } .sub-menu { position: absolute; top: 100%; left: 0; display: none; } .sub-menu-item { cursor: pointer; } .sub-menu-item:hover { background-color: #f0f0f0; } .show { display: block; } </style>

In this example, we have a dropdown component with a main menu item and a sub-menu for item 2. Clicking on "Item 2" toggles the visibility of its sub-menu. You can extend this example to add more levels of dropdown menus as needed.