Vue.js: Efficiently handling multiple buttons within a Dropdown menu

I am currently working on a Vue.js Project and have a Dropdown component. Here is the code snippet:

<template>
    <v-menu close-on-click transition="slide-y-transition">
        <template v-slot:activator="{ on, attrs }"> 
            <v-btn  color="primary" v-bind="attrs" v-on="on">
                Menu
            </v-btn>
        </template>
        <v-list>
            <v-list-item v-for="(item, index) in menuItemsMisc" :key="index">
                <v-list-item-title>
                    <v-btn block color="white">{{ item.title }}</v-btn>
                </v-list-item-title>
            </v-list-item>
        </v-list>
    </v-menu>
</template>
<script>
export default {
    name: 'MenuBar',
    data() {
        menuItemsMisc: [
            {   title: 'Visit Website' },
            {   title: 'Logout' },
            {   title: 'Purchase' },
        ]       
    }
}
</script>

I have specific functions in mind for each button:

Visit Website -> Link to a Website

Logout -> Execute a function

Purchase -> Display a Purchase Modal

I used to handle these buttons differently with page routing, but I believe it might not be the most efficient approach for buttons with distinct functionalities. How should I proceed?

<v-list-item v-for="(item, index) in menuItemsPages" :key="index">
    <v-list-item-title>
        <v-btn :to= "'/' + item.url" >{{ item.title }}</v-btn>
    </v-list-item-title>
</v-list-item>

Answer №1

(not vuetify)I'm not certain if this approach is ideal, but you could give it a shot:

Within my router, there exists an About page that functions as expected! Furthermore, upon selecting alternative options, I can observe the outputs in the console. If you can implement this code in vuetify, it should function smoothly.

<template>
  <div class="home">
      <select v-model="selectedValue">
        <template v-for="(item, index) in menuItemsMisc">
            <option :value="item.title" :key="index"> {{item.title }} </option>
        </template>
      </select>
  </div>
</template>

<script>
// @ is an alias to /src


export default {
  name: 'Home',
  data() {
    return {
      selectedValue : "",
      menuItemsMisc: [
            {   title: 'Visit Website' },
            {   title: 'Logout' },
            {   title: 'Purchase' },
        ]       
    }
  },
  watch: {
    "selectedValue": function() {
      if (this.selectedValue === "Visit Website") {
        this.$router.push({name: "About"})
      }
      else if (this.selectedValue === "Logout") {
        this.doSomething()
      }
      else {
        this.purchase()
      }
    }
  },
  methods: {
    doSomething() {
      console.log("I AM DOING SOMETHING")
    },
    purchase() {
      console.log("hello purchase")
    }
  }
 
}
</script>

Answer №2

To implement this functionality, you can create a function for each element in the menuItemsMisc array and then pass it to the @click event of the v-btn.

<template>
  <v-menu close-on-click transition="slide-y-transition">
    <template v-slot:activator="{ on, attrs }">
      <v-btn color="primary" v-bind="attrs" v-on="on">Menu</v-btn>
    </template>
    <v-list>
      <v-list-item v-for="(item, index) in menuItemsMisc" :key="index">
        <v-list-item-title>
          <!-- Pass `item.click` to `@click` -->
          <v-btn block color="white" @click="item.click">{{ item.title }}</v-btn>
        </v-list-item-title>
      </v-list-item>
    </v-list>
  </v-menu>
</template>
export default {
  name: "Home",
  data: () => ({
    menuItemsMisc: [
      {
        title: "Visit Website",
        click: () => {
          // Go to a route
          this.$router.push({ name: "About" });
        }
      },
      {
        title: "Logout",
        click: () => {
          // Call a function
          console.log("Logging out...");
        }
      },
      {
        title: "Purchase",
        click: () => {
          // Show modal
          console.log("Showing purchase modal");
        }
      }
    ]
  })
};

Check out a demo here.

Answer №3

To enhance your array of objects, simply attach a function to each item like this :

menuItemsMisc: [
                { title: 'Go to Website', fn: () => { this.$router.push('/') }},
                { title: 'Sign Out'      , fn: () => { /* Add your custom code here */ }},
                { title: 'Buy Now'       , fn: () => { /* Implement your own logic */ }},
            ]

Then, make use of the function with an event listener upon clicking :

<v-btn @click="item.fn" >{{ item.title }}</v-btn>

Answer №4

I found a great solution by combining elements from both responses!

data: () => ({
  menuItemsMisc: [
    { title: "Save Template" },
    { title: "Edit Attendance" },
  ],
)}




watch: {
  selectedValue: function () {
      if (this.selectedValue === "Save Template") {
        this.saveAsTemplate(this.topListWithName);
      } else if (this.selectedValue === "Edit Attendance") {
        this.updateAttendance = true;
      }
    },
  },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to pass data to another page by clicking on a row, the result is that the data appears to be empty

I have been using the MUI-Datatable component, which is able to navigate to the next page. However, when I try to view the data on the History page, nothing appears. How can I resolve this issue? Data transfer to another page: Even though I can see the d ...

"Switching to a new request in jqgrid will automatically cancel the current

I am using a jqgrid on my website to display data in JSON format retrieved from the server. The grid includes some blank cells which users can double-click on to update the data. However, I have encountered a problem where if I click too quickly on multipl ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this. Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a p ...

Stopping a JavaScript promise.all() based on a certain condition

Here's a snippet of code I'm working with: let promiseList = [] for (let i in data) { let promise = checkIfMember(data[i].tg_id, chatId).then(res => { if (res) { //if the user has a undefined username ...

What steps should I take to resolve the "StrictMode has found deprecated findDOMNode" error?

Whenever I trigger the button to open the drawer, my console displays the warning message '' findDOMNode is deprecated in StrictMode'' The container for the button component is called Sidenav import Sidenav from './Sidenav'; ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

Using JavaScript to bring in npm packages

My understanding of javascript modules is still lacking. I recently embarked on a new project that required a library from npm. https://www.npmjs.com/package/random-color-pair After running npm i random-color-pair This created a "node modules" folder wh ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

Issue with Mongoose Promise failing to transfer data to the following chain

When querying MongoDB using mongoose with promises, I encounter an issue where the result is only accessible in the initial .then(function(results){ // can send the result from here..}). However, when I manipulate the results and attempt to pass them to th ...

Problem with validation in jQuery not being compatible with Kendo Button (sample code provided in jsfiddle)

It took me some time to figure out that the reason jquery-validate wasn't functioning in my Kendo Mobile application was because my submit button was a Kendo Button. Check out this jsfiddle for illustration: DEMO <div id="phoneApp" style="displa ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

developing a custom modal using a button in a React project with Material UI

Hello everyone, I have a question regarding React. I am fairly new to React and need some assistance with adding a new function that creates a Modal. I want to call this function onClick when the add icon is pressed (line 43). Any help would be appreciated ...

Tips for sequentially arranging and rearranging an array of numbers, even when duplicates are present

Encountered a perplexing issue that has me scratching my head in an attempt to visualize a solution. Currently, I am working with an array of objects that appears as follows: let approvers = [{order:1, dueDate: someDate},{order:2, dueDate: someDate}, ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...

Is there a way in WebStorm to create a "virtual" folder for conveniently organizing and hiding config files, or perhaps a feature that allows for easily toggling visibility of certain files?

I have a strong dislike for having all my configuration files cluttering up the root directory. These files are usually set up at the beginning of a project and rarely need to be changed. While I can hide them in WebStorm, it becomes a hassle to unhide the ...

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...