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

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

getStaticProps only runs on IIS after the entire page is refreshed

Using the nextjs getStaticProps feature in my project has been smooth sailing so far. However, after uploading the Static files to IIS, the feature seemed to stop working until I configured a urlRewrite module on it. I noticed that when initially visiting ...

Exploring the power of Angular 2 Directive scopes

When it comes to Angular2, Directives do not come with "scopes", unlike Components. However, in my specific case, I require a Directive to establish a scope. Take a look at my App component - it contains an HTML template, and the foo directive could potent ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...

Deactivate the date when it reaches 8 in the current date count using ajax, php, and mysql

I want to prevent users from selecting a specific date after it has been chosen 8 times. Currently, when the date is selected for the 9th time, an alert box pops up. Instead of the alert box, I would like to disable that particular date selection altogethe ...

Issue with Material-ui Autocomplete: onChange event not firing when value is updated in onHighlightChange

I have been customizing Material UI's Autocomplete by adding a feature that allows users to move options to the input using keyboard events (Arrow keys up and down). Then, the user should be able to select an option by pressing the ENTER key. I am fa ...

The AJAX request was a success, but unfortunately there is no usable data available

After submitting the registration form, jQuery sends the data to register.php, which then responds with JSON data for jQuery to process. Everything seems to be functioning correctly as users are successfully registered. The network response tab shows that ...

Unable to open new window on iOS devices using $window.open

alertPopup.then (function(res) { if(ionic.Platform.isAndroid()) { $window.open('android_link_here', '_system') } else if(ionic.Platform.isIOS()) { $window.open('ios_link_here', '_system& ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

Which is better: Utilizing Ajax page echo or background Ajax/direct HTML manipulation?

I am facing a dilemma and I could really use some guidance. Currently, I am in the process of developing an ordering system using PHP/Smarty/HTML/jQuery. The main functionality revolves around allowing sellers to confirm orders on the site. My goal is to ...

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

Using Angular JS to dynamically load an HTML template from a directive upon clicking a button

When a link is clicked, I am attempting to load an HTML template. A directive has been created with the templateUrl attribute to load the HTML file. Upon clicking the link, a function is called to append a custom directive "myCustomer" to a pre-existing di ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

When working with Typescript, an error may occur related to index types even though the constant object and its

I am struggling with understanding TypeScript, specifically when it comes to a problem I encountered. Hopefully, someone can shed some light on this for me. My issue revolves around a functional component that is responsible for displaying the correct com ...

Transforming button properties into a JSON format

I am currently in the process of developing a web application using node.js and mongodb. Within my app, there is a table that dynamically populates data from the database using a loop. I encountered an issue with a delete function that I implemented base ...

Make sure to attach a resize event handler just once

I am working with a widget that inserts a div element into the DOM. This div requires some JavaScript to handle the resize event effectively. Here's the issue: The widget may be added multiple times on the same page, but I want to avoid adding re ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Unable to implement new ecmascript decorators within typescript version 2.4.2

Check out this example code: function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { descriptor.enumerable = value; }; } class A { @enumerable(false) a: number = 1 b: number ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Encountering challenges with CORS implementation in a test application

I am struggling with an issue while trying to send a request to a website for ping. I have tried using jsonp, but it's not working as expected. I attempted to implement cors, but I keep getting the error message "No 'Access-Control-Allow-Origin&a ...