How to implement a dropdown menu in Vue.js



Image not found!!

Implementing a dropdown menu in Vue.js involves creating a component that manages the state of the dropdown (open or closed) and renders the menu items accordingly. Here's a simple example to get you started:

  1. Create a Dropdown component:

    vue
    <!-- Dropdown.vue --> <template> <div class="dropdown"> <button @click="toggleDropdown">Toggle Dropdown</button> <ul v-if="isOpen" @click="selectItem"> <li v-for="item in items" :key="item.id">{{ item.label }}</li> </ul> </div> </template> <script> export default { data() { return { isOpen: false, items: [ { id: 1, label: 'Item 1' }, { id: 2, label: 'Item 2' }, { id: 3, label: 'Item 3' }, ], }; }, methods: { toggleDropdown() { this.isOpen = !this.isOpen; }, selectItem(event) { const selectedItem = event.target.textContent; // You can emit an event or perform any action with the selected item console.log(`Selected Item: ${selectedItem}`); this.isOpen = false; // Close the dropdown after selecting an item }, }, }; </script> <<style scoped> .dropdown { position: relative; } ul { list-style-type: none; padding: 0; margin: 0; position: absolute; top: 100%; left: 0; background-color: #fff; border: 1px solid #ccc; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } li { padding: 8px; cursor: pointer; } </style>
  2. Use the Dropdown component in your parent component:

    vue
    <!-- App.vue --> <template> <div id="app"> <Dropdown /> </div> </template> <script> import Dropdown from './components/Dropdown.vue'; export default { components: { Dropdown, }, }; </script> <style> #app { text-align: center; margin-top: 60px; } </style>

This is a basic example, and you can customize it further based on your needs. The Dropdown component uses a button to toggle the dropdown state and a list of items that are displayed when the dropdown is open. You can enhance it with animations, styles, and additional features as required for your application.