Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format:

Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...]

I wish to include an on/off button for each row of the data, with each button having its own independent state. I plan to enhance its functionality later and prefer the appearance of v-btn, so I would like to stick with it if possible.

The code for the button is as follows:

<v-btn
    color="primary"
    variant="outlined"
    @click="trackBill"
    >{{ this.trackedBtnText }}</v-btn>

The scripts are:

<script>
export default {
    data: () => ({ bills: [], trackedBtnText: 'Track', tracked: false }),
    methods: {
        async showBills() {
            this.bills = await showBills(this.keywords);
        },
        trackBill() {
            this.tracked = !this.tracked;
            this.trackedBtnText = this.tracked ? 'Tracked' : 'Track';
        },
    },
};
</script>

Currently, when I click one button, the text changes on EVERY button. I am seeking a way to maintain individual variables for each function, as they will be involved in making API queries based on the retrieved data which may hold additional information later in development.

Answer №1

When you find yourself needing to repeat a task multiple times, it's best to utilize v-for to avoid unnecessary code repetition.

Simply place your configuration data into objects within an array. Each object should contain all the necessary information to define a button, such as a title, state, CSS classes, and any other data required for queries:

      buttonData: [
        {title: 'Column 1', checked: false},
        {title: 'Column 2', checked: true},
        {title: 'Column 3', checked: false},
      ]

You can then use v-for to render these buttons dynamically:

        <v-btn
          v-for="button in buttonData"
          :key="buttonData.title"
          @click="$event => button.checked = !button.checked"
        >
         {{ button.title + ' is ' + (button.checked ? 'on' : 'off') }}
        </v-btn>

This approach allows you to easily manipulate the states of the buttons through the array.

It's worth noting that buttons are not ideal for toggle switches. Consider using switches or checkboxes instead.

If you're looking for a sample code snippet, here's one for Vue 2:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data(){
    return {
      buttonData: [
        {title: 'Column 1', checked: false},
        {title: 'Column 2', checked: true},
        {title: 'Column 3', checked: false},
      ]
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40262f2e3400766e38">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="85f3f0e0f1ece3fcc5b7abfd">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">
</head>

<body>
  <div id="app">
    <v-app>
      <v-main>
        <v-btn
          v-for="button in buttonData"
          :key="buttonData.title"
          :color="button.checked ? 'primary' : 'secondary'"
          class="ma-4"
          @click="$event => button.checked = !button.checked"
        >{{ button.title + ' is ' + (button.checked ? 'on' : 'off') }}</v-btn>
      </v-main>
    </v-app>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbbdbeae8bf9e5b3">[email protected]</a>/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="37414252435e514e7705194f">[email protected]</a>/dist/vuetify.js"></script>

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

Effortlessly move and rearrange various rows within an HTML table by utilizing JQuery alongside the <thead> elements

My JsFiddle has two tables and I want to switch rows <tr> between them using Jquery. However, due to the presence of the <thead> tag, it is not functioning properly. I suspect that the issue lies with the items in the selector, but I am unsure ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

Discovering identical elements within a list in Python through index-based location scanning

Check out this JavaScript code that can determine whether there are any duplicate elements in an array. function findDuplicates(arr) { let seen = []; for (let i = 0; i < arr.length; i++) { if(seen[arr[i]] === 1) { ...

What steps should I follow to successfully launch my Larvel and Vue project using Inertia?

I have tried multiple free servers, but every time I attempt to run npm install, I encounter an error stating that the vendor vue file is not found. Is there anyone who can provide a course or blog with detailed deployment steps for any server? I was able ...

The nodejs server failed to respond to my request, displaying "undefined" instead

I have encountered some challenges while hosting my website on Firebase and Heroku Here are the issues I am facing: Initially, I am encountering CORS errors when trying to post data from a Firebase hosted URL to a server hosted on Heroku Even after re ...

Unable to display an image element in fullscreen within a modal that is already fullscreen

I am facing an issue with my modal that is designed to occupy the full width and height of a browser. Inside this modal, there is an image enclosed within a div along with some other elements. My goal is to make the image go full screen in the browser, aki ...

Error: ...[i] has not been defined

What seems to be the issue with this part of the script: function refreshLabels() { // loop through all document elements var allnodes = document.body.getElementsByTagName("*"); for (var i=0, max=allnodes.leng ...

What is the best way to halt an event using jQuery?

My question is about handling events on a webpage. I am interested in triggering a jquery method when the user clicks a link to navigate away from the page. In this method, I need to perform some checks before allowing the user to leave, so I plan to use: ...

Retrieve the present time of an ongoing CSS3 animation

I've been trying to retrieve the current time of a running animation, but I haven't had any luck so far. I can easily grab the start time using: myelement.addEventListener('webkitAnimationStart', function (evt){ console.log(evt.elaps ...

Why doesn't the div click event trigger when the mouse hovers over an iframe?

My dilemma involves a div element with a click event. When the div is positioned over an iframe area (closer to the user than the iframe), the click event fails to trigger. However, if the div is located elsewhere and not above the iframe, the click event ...

Customize your click event with conditional styling in React

When the onClick event is triggered, I am attempting to modify a class by calling my function. It appears that the function is successfully executed, however, the class does not update in the render output. Below is the code snippet: import React from &ap ...

The MomentJS difference calculation is incorporating an additional hour

I am currently working on a project that involves time calculations. const currentCETTime = moment.tz('2020-03-18 15:58:38', 'Europe/Madrid'); const limitCETTime = moment.tz('2020-03-18 18:00:00', 'Europe/Madrid') ...

When modifying the data, the computed information does not update immediately

I have created a Vue.js demo, please take a look below: <template> <div class="index"> <Row> <Select v-for="(select, s_index) in select_data" v-model="selected_data_obj[s_index]" :key="'s-'+s_index" style="widt ...

How can the vertical scroll bar position be reset in Material-Table when pagination is activated?

Whenever I scroll up or down in my Material-Table, and then switch pages, the vertical scroll bar doesn't reset to the top of the table. Instead, it stays where it was before changing the page, causing confusion for users. The only mention of scroll ...

Customizing the label styles within MUI's Chip component

Incorporating React with MUI's library has been a seamless experience for me. One of the key MUI components I have integrated is the Chip Within this particular Chip, there lies the label attribute, offering the option to showcase a text f ...

Using JavaScript to Retrieve URLs and Identify HTTP Status Code 403

In my JavaScript code, I am attempting to retrieve a 403 Forbidden response code using JavaScript. I have tried modifying the following code, but it does not seem to be working for me: <script type="text/javascript"> var request = new XMLHttpRequ ...

Trouble accessing value in Vue.js

I'm having an issue where I am unable to access this.active in my method delete. What could be causing this problem? data () { return { ride: { user: {}, location: {}, type: {} }, active: false } }, methods: { delete () ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Executing an external Python script within a Vue application's terminal locally

Hello, I am new to using Vue.js and Firebase. Currently, I am working on creating a user interface for a network intrusion detection system with Vue.js. I have developed a Python script that allows me to send the terminal output to Firebase. Right now, I a ...

jQuery not functioning properly when attempting to add values from two input boxes within multiple input fields

I am facing an issue with a form on my website that contains input fields as shown below. I am trying to add two input boxes to calculate the values of the third input box, but it is only working correctly for the first set and not for the rest. How can ...