Is there a way to individually apply loading to only the button that has been clicked in vuejs?

One problem I am facing is that when I click a specific button in a table, all buttons end up in loading mode. The table loops and displays data from an API, with a button embedded in each row. Upon clicking the button, it should send the ID of the clicked button and remain in loading until it receives the necessary function data to be printed. Below is the code snippet:

<table id="customers">
  <tr>
    <th>{{$t('message.numberReport')}}</th>
    <th>{{$t('message.periodFrom')}}</th>
    <th>{{$t('message.periodTo')}}</th>
    <th>{{$t('message.printButton')}}</th>
  </tr>
  <tr v-for="(item,index) in getReportInfo" :key="index">
    <td>{{ item.id }}</td>
    <td>{{ item.periodFrom }}</td>
    <td>{{ item.periodTo }}</td>
    <td>
      <v-btn
        class="primary"
        :loading="loading"
        :disabled="loading"
        @click="fetchGetReportDetailed(item)"
      >{{ $t('message.printButton')}}</v-btn>
    </td>
  </tr>
</table>                    

If you have any suggestions on how to resolve this issue, I would greatly appreciate your input. You can view a visual example here.

Answer №1

Utilizing the index of an item in a list.

To keep track of the index when an item is clicked, you can create a new variable in your data called indexClicked .

data () {
    return {
        // Choose a predefined value, not 0 as the index could be 0.
        indexClicked: undefined // Set a default value
    }
}

When a button is clicked, pass the index value:

<td>
<v-btn class="primary"
       :loading="loading && indexClicked === index" 
       :disabled="loading && indexClicked === index" 
       @click="fetchGetReportDetailed(item, index)">
       {{ $t('message.printButton') }}
</v-btn>
</td>

In your

fetchGetReportDetailed(item, index)
method, assign the index to this.indexClicked:

fetchGetReportDetailed (item, index) {
    // Your logic here
    this.indexClicked = index;
}

This approach should work, but if you require further assistance, kindly provide additional code snippets.

Note: If handling multiple conditions in :disable becomes complex, consider creating a method that returns true or false based on the condition

loading  && this.indexClicked === index
.

Best of luck!

Answer №2

To ensure each row has its own loading property, you can add a new property called loading to each row within the mounted hook:

mounted(){
   this.getReportInfo=this.getReportInfo.map(rep=>{
               rep.loading=false;
             return rep;
         });
}

Then in the template, include:

   <tr v-for="(item,index) in getReportInfo" :key="index">
                            <td>{{ item.id }}</td>
                            <td>{{ item.periodFrom }}</td>
                            <td>{{ item.periodTo }}</td>
                            <td><v-btn  class="primary" :loading="item.loading" :disabled="loading"  @click="fetchGetReportDetailed(item,index)" >{{ $t('message.printButton')}}</v-btn></td>
                        </tr>

In the fetchGetReportDetailed method:

fetchGetReportDetailed(item,index){

....

this.getReportInfo[index].loading=true;
this.$set(this.getReportInfo,index,this.getReportInfo[index])
}

Answer №3

To enhance the organization of your code, consider creating a separate stateful component for the tr element that displays the data. Within this component, you can then call the necessary function.

By implementing this approach, each item in the array will have its loading state managed locally within its respective component.

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 fetch JSON data using the Angular 2 `http.get()` method, the data returned is undefined and the component does not reflect any

My http-data.service is set up to accept json for output in the component template. Initially, the console displays that the first few calls return undefined, while subsequent calls start returning json. However, upon checking the component, it is evident ...

Error message "invalid function call this.job.execute" when using Node.js node-schedule npm package

Having just started with nodejs, I created a nodejs program and set it to run every minute using the node-schedule library. However, after running for some time and producing several logs in the console, I encountered an error stating that this.job.execute ...

Use of ng-if in combination with recursive directives does unexpected behavior

I have a situation where I am using two recursive directives inside ui-bootstrap tabs. In order to optimize performance, I want the directive to only load when its corresponding tab is active. To achieve this, I am using ng-if on the directive like this: & ...

Add an element to an array using the `push` method in JavaScript

I am currently studying the code for creating a canvas circle motion trail effect. I am a bit puzzled by the push(x:Pos,y:Pos) within thestoreLastPosition() function in the sample code provided below: ctx = canvas.getContext('2d'); var xPos = - ...

How can I fetch the ID from a posted AJAX request in PHP?

Is there a way to retrieve the data from an ajax request in PHP? I am able to successfully return a string of data using ajax, but I'm having trouble accessing the variable passed as a json object. How can I access a json object that only contains one ...

Json data integrated dropdown menu

I have successfully retrieved data from a Json array and displayed it in a dropdown list. However, I am facing an issue where I want to only show the name of the city instead of both the name and description. If I remove cities[i]['description'], ...

Implement Dynamic Filters in a Vue Component

How can filters be programmatically applied to select values? During each iteration of records and columns, I am checking if the column ID starts with 'd', indicating it's a datetime field. In such cases, I want to apply the humanize filter ...

An automated feature that smoothly transitions a large image onto the screen

I came across a plugin, possibly a slideshow plugin, that smoothly slides a large image along the y-axis. It's hard to explain, but imagine the visible image is only 600px by 300px, while the actual image is 600px by 600px. This plugin would scroll t ...

Creating a JavaScript function to imitate the pressing of the Enter

I am attempting to mimic the pressing of the Enter key using JavaScript within a specific TextArea. Below is the code I have written: function enter1() { var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

What is the reason behind arr.reverse() flipping the original array?

My goal is to reverse an array and store the reversed version in a new array without altering the original array. Here is the code I am using: var arr= ["1", "2", "5"] var arrTwo = arr.reverse(); console.log(arrTwo) \\ ["5" , "2" , "1"] console. ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

Using `ng-model` within an Angular directive

Looking to achieve bi-directional binding in an Angular directive Here is my current approach: angular.module('myapp',[]),directive('mydirective', function() { var directive = {}; directive.restrict = 'E'; directi ...

Easily create an HTML page from a multitude of intricate JavaScript objects with this convenient method

In my project, I am looking to dynamically generate an HTML page based on JavaScript objects and then present it to the user. For example: var mybutton = { id: 'button_1', x: '0', y: '0', width: '100', h ...

Getting the output from AJAX when the onreadystatechange event occurs

Struggling with retrieving a value from a function and storing it in a variable? Getting an "undefined" result due to JavaScript's asynchronous nature? Unsure how to fix this using "callbacks" or "promises"? Check out the code snippet below. The goal ...

I created a customized version of jQuery tabs, but I am looking for an external link to display the tab content and to style the original navigation

I've been experimenting with modifying a tabs script in jQuery that I came across. It seems like my attempt to enhance it has made things more complex than necessary. While I know creating tabs with jQuery is simple, I wanted to create my own version ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...

Error: Import statement is not allowed outside a module while running on live server

//this is the Greetings.js file import React from "react"; function DisplayGreetings() { return ( <div><h1>Welcome</h1></div> ) } export default DisplayGreetings //This is the Main.js file import React,{Compone ...

What sets onEnter apart from onStart in ui-router?

I am transitioning to the latest version of ui-router (1.0.0-alpha.5) and I am exploring how to utilize the onEnter hook versus the onStart hook: $transitions.onStart() as well as $transitions.onEnter() In previous versions, we only had the event $sta ...

Troubleshooting Issue with Internet Explorer failing to update Asp.Net MVC3 Partial View

I am experiencing an issue with a page that includes a div for a partial view loaded via an ajax request. $.ajax({ url: 'CompleteSessions', success: function (data) { var selector = $('#complete-session-sect ...