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

The process of integrating a Loader in Javascript

I am in need of a simple "page loading" animation while my photo is being uploaded. Unfortunately, when I tried using the "blockUI" JavaScript for this purpose, it didn't seem to work with my form. For uploading the image, I have employed a div as a ...

Steps for integrating external components into Laravel 5.3 with VueJs Routes

I am currently working with Laravel 5.3 and utilizing the built-in VueJs components. At this point, my goal is to implement routes into my project. I have attempted to use the following code, but unfortunately, it is not functioning as expected. const No ...

Ways to display a US map using d3.js with state names positioned outside each state and pointing towards it

Currently, I am working with d3.js and d3-geo to create a map of the USA. My goal is to display the names of some states inside the state boundaries itself, while others should have their names positioned outside the map with lines pointing to the correspo ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

Having trouble loading AngularJS 2 router

I'm encountering an issue with my Angular 2 project. Directory : - project - dev - api - res - config - script - js - components - blog.components.js ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

A step-by-step guide on making a list item clickable and redirecting to a URL using Vue.js

Utilizing vue.js, I have successfully configured a navigation bar with multiple list elements. However, I am seeking guidance on how to redirect one of the list elements to an external website, such as https://www.google.com/. Within my router file, each e ...

Tips for personalizing react-show-more text length with Material-UI Icons

In my SharePoint Framework webpart using React, I am currently utilizing the show more text controller. However, I am interested in replacing the "Show More" and "Show Less" string links with the ExpandMore and ExpandLess Material UI icons. Is there a way ...

Order Up: Vue Draggable Next feature keeps your lists in line

I need to maintain the order of two lists in local storage so that their positions are saved and retrieved between sessions. In my Vue 3 TS project, I am utilizing this library. Check out the code snippet below: <template> <div> <h3> ...

AngularJS: updating a module

I recently started learning AngularJS and I need some guidance on how to refresh the data in a table within a module (specifically, a list of names and post codes). Below is the script where I am trying to reload the JSON file upon clicking a button: < ...

Implementing Vuejs sorting feature post rendering

Currently, I have elements linked to @click event listeners. <th @click="sort('dateadded')" class="created_at">Date Added I am looking for a way to automatically trigger this sorting function when the Vue.js component renders, so that th ...

Utilizing Azure SDK to send an email

In my Node.js project, I am currently utilizing azure-graph: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId, { tokenAudience: 'graph' } ...

Is the server delivering an unexpected response?

Implementing a post request using the fetch API in React JS, I provide a URL to the server from the frontend. The server then utilizes this URL to make an API call to Clarifai API. The expected response is received from the API; however, when transferring ...

Unable to store user data in the MongoDB Database

I'm currently facing an issue while trying to store user information in my MongoDB database. Everything was working fine until I implemented hashing on the passwords using bcrypt. After implementing password hashing, I am encountering difficulties in ...

Retrieve binary data of an image from an API and render it on an HTML page

I have been working on storing images in a MongoDB database and trying to display the response I receive from an Express API as an image on the client side. The image source URL looks like this: src="/image/data/5a44dde172aa021d107e7d33" When I try to wr ...

How to effectively filter nested arrays within Mongoose Populate function

I received the following object from a Mongoose query: let systems = [ { "maxUserLevel": 1, "subsystems": [ { "sections": [], "name": "apple" ...

enhancing angular directives with data binding while replacing HTML content inside the compile function

I am currently attempting to develop a directive that will substitute an input field with a custom-made input field. Unfortunately, I am encountering challenges with getting the data binding to function properly, as the model does not display in the direct ...

Step-by-step guide for activating a text box when a check box is marked

I'm looking to activate and deactivate two text boxes when a check box is selected. Currently, only one text box is enabled when the check box is checked. How can I modify my code to enable and disable two text boxes based on the check box status? Her ...

What could be causing the EBUSY: resource busy or locked, open errno: -4082 error to appear while trying to build storybook 7 in next.js 13?

While attempting to create a storybook, I encountered the following error in my project: [Error: EBUSY: resource busy or locked, open 'C:\Users\ali\Desktop\Works\Design Systems\projects\storybook-test2\node_modu ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...