Sending information to a single component among several

I'm developing a custom DownloadButton component in VueJS that features an animation when clicked and stops animating once the download is complete. The DownloadButton will be utilized within a table where it's replicated multiple times. I intend to keep the download functionality within the parent component. However, the issue arises when changing the loading state affects all instances of the DownloadButton rather than just the one that was clicked.

Parent Component:

<DownloadButton @click.native="download" :loading="loading"></DownloadButton>
<DownloadButton @click.native="download" :loading="loading"></DownloadButton>
<DownloadButton @click.native="download" :loading="loading"></DownloadButton>

methods: {
   download() {
       this.loading = true
       // waiting for the download process to complete...
       this.loading = false
   }
}

Answer №1

Make sure to keep an eye on the loading status of every single button, not only the overall loading state.

Here's a simple and fast example that demonstrates what you're looking for:

Vue.component("download-button", {
template: "#dbTemplate",
  props: ['loading'],
  computed: {
  stateText() {
        return this.loading ? 'Loading...' : 'Load';
    }
  }
});

new Vue({
  el: "#app",
  data: {
    resources: [
    { date: new Date(), url: "some-url1" },
      { date: new Date(), url: "some-url2" },
      { date: new Date(), url: "some-url3" },
      { date: new Date(), url: "some-url4" }
    ],
    resourceStates: {}
  },
  methods: {
  downloadResource(resource) {
    this.$set(this.resourceStates, resource.url, true);
    new Promise((resolve, reject) => {
          setTimeout(() => resolve(new Date()), 1000);
      }).then((date) => {
      resource.date = date;
      this.$set(this.resourceStates, resource.url, false);
      })
    },
    isLoading(resource) {
    return !!this.resourceStates[resource.url];
    }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e2e1f1d4a6baa1baa5a2">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <div v-for="res in resources" :key="res.url" style="padding: 10px 0">
    {{ res.date.toLocaleString() }}&nbsp;
    <download-button  @click.native="downloadResource(res)" :loading="isLoading(res)">
    </download-button>
  </div>
</div>

<script type="text/template-x" id="dbTemplate">
<button :disabled="loading">
  {{ stateText }}
</button>
</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

Is your list rendering in Vue.js with AJAX ready to go?

At this moment, my Vue.js component is retrieving data from an Elasticsearch query and displaying it in a list like this: <li v-for="country in countries">{{ country.key }}</li> The issue I am facing is that I want to show users only a snippe ...

Using angularjs to include content from other files is known as

As I delve into the concept of creating directives in AngularJS, I am faced with the imminent end of Angular 1.x and the rise of Angular 2.x. The shift seems daunting, but I am determined to bridge this gap seamlessly. In my quest for clarity, I stumbled ...

Ways to customize the TextInput component in React-Admin

I am facing a challenge with overriding specific fields in my custom theme. It seems that setting the custom theme also overrides other fields unintentionally. I attempted to use useStyles to resolve this issue, but unfortunately, it did not work as expec ...

Vue Js image loading issue

I'm having trouble referencing an image to display in my view. I keep getting this error message: "InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': 'product.images[0].filename' is not a valid attribut ...

What is the best way to utilize regex for replacing a string within Node.js environment?

I'm struggling with updating the string in my code. Essentially, I have a .php file and I want to modify some constants using the replace package. The output of my current code is: // Current Output define('DB_NAME', 'foo'); // ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Guide on toggling a modal in a nested component with a prop in Vue.js

Here is my current child component setup: <Edit @fetchInfo="fetchInfo" :agencyData="agency" :dialogEdit.sync="dialogEdit" ></Edit> This component essentially features a modal. Initially, the modal is hidden: data(){ r ...

Is it possible to modify a JavaScript array variable without having to refresh the page by utilizing Ajax?

Is it possible to update a JavaScript array variable without having to reload or refresh the page? I have an existing list of data in an array, and I retrieve additional data using PHP and Ajax. Now I want to add the new data obtained from PHP Ajax to th ...

How to send index to child event listener from parent component in Vue.js

Within a v-for loop, I am iterating over a list of objects: <div v-for="(element, index) in myArray"> <child @event-fired="handleEvent(index, dataFromChild)"></child> </div> When the event is fired from the child component, I ...

Ensure that background elements do not become the focus when using MUI backdrop

Currently, we are implementing screen dimming when a custom dialog is open using MUI backdrop. However, even though the screen is "grayed-out," users can still access the items with the keyboard. In the image below, you can see how I move from "show backd ...

NextJS hot reload with Docker is a powerful combination for seamless development environments

I've encountered issues trying to configure hot reload with Docker and NextJS. When I make changes and save a file, the server does not reload. Below is the contents of the docker-compose.yml: version: '3' services: mainapp: build: ./ ...

What is the best way to locate the final text node within the <p> element?

Looking at the code below, my goal is to identify and retrieve the text node that serves as the last child element. <p class="western" style="margin-bottom: 0.14in"> <font color="#000000"> <font face="Arial, serif"> <font ...

How can I pass function arguments dynamically to a nested function in Node.js?

Currently using Node 6.11.0, I am attempting to accomplish the following dynamically: const parentFunc = (arg1, arg2, arg3, arg4) => { childFunc('foo', arg1, arg2, arg3, arg4); }; I have attempted this method (without success): const pare ...

Adding style using CSS to a dynamically generated table row in Vue.js

Currently, I am working with a table that dynamically generates rows using v-for: <table> <tr><th class='name'>Name</th><th>Surname</th></tr> <tr v-for='data in datas'><td class=&a ...

Is it possible to combine ng-switch and ng-if directives in Angular?

I attempted to combine the angular ng-switch and ng-if directives, but it doesn't seem to be functioning properly. Here is what I tried: <div data-ng-if = "x === 'someValue'" data-ng-switch on = "booleanValue"> <div data-ng-swit ...

Assistance in configuring Zurb Foundation 5 for optimal integration with Laravel

As a relatively new user to Laravel with previous experience using older versions of Foundation, I am currently in the process of setting up a new Laravel project. My goal is to integrate the Foundation framework into my project, but I find myself a bit co ...

Encountering timeout issues with Next.JS fetch and Axios requests on Vercel production environment

I've been encountering an issue where I am unable to fetch a specific JSON data as it times out and fails to receive a response on Vercel deploy. The JSON data I'm trying to fetch is only 18KB in size and the fetch request works perfectly fine in ...

Is there a way to modify the color of a specific section of a font icon?

Currently, I am in the process of implementing an upvote button using fa fa signs. However, I have encountered an issue where the background color of the up vote button is bleeding outside of the sign (possibly due to padding on the icon), and I am strivin ...

Ways to update a component from another in React

My React code includes an Employees page that renders both a Table component and a Filter component. The Filter component manipulates some data stored in the Employees page, updates the Filter's state through useEffect, and passes the data as a prop t ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...