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

Place the div's scrollbar at the beginning of its content

Recently, I put together a custom CSS modal that includes a scrollable div (without the modal itself being scrollable). Interestingly enough, when I initially open the modal, the scrollbar of the div starts at the top as anticipated. However, if I scroll d ...

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...

I'm struggling to understand the folder arrangement and the system is telling me it can't locate my file

I'm having trouble identifying what might be causing issues with my file structure. Currently, I am using Aurelia for the front end and node for the server. I attempted a fix by performing a join operation, which resolved some of the problems. However ...

Ways to recycle a section of Javascript for multiple uses on a single page

As a newcomer to website building, I have a query regarding the usage of a JavaScript function designed for a slideshow. My one-page website comprises multiple slideshow units with their own divs, holders, and counters (e.g., 1/4). A JavaScript code contro ...

Is there a way to view Deno's transpiled JavaScript code while coding in TypeScript?

As I dive into Typescript with Deno, I am curious about how to view the JavaScript result. Are there any command line options that I may have overlooked in the documentation? P.S. I understand that Deno does not require a compilation step, but ultimately ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

Utilizing Node Js and Socket.Io to develop a cutting-edge bot

Is it possible to run JavaScript with Node.js without launching Google Chrome from various proxies? Can someone provide a sample code for this task? For example, you can find a similar project here: https://github.com/huytd/agar.io-clone Another project c ...

Exploring the power of $j in JavaScript

Could someone please explain what the $J signifies in this snippet of javascript code? if ($J('.searchView.federatedView.hidden').attr('style') === 'display: block;' || $J('.searchView.federatedView.shown').length ...

What is the process for releasing an NPM package to the NPM registry rather than the GitHub registry?

I have developed an NPM package available at - (https://github.com/fyndreact/nitrozen) The package was successfully published on the Github registry (), but I am looking to publish it on the NPM registry. However, I cannot locate the package in the NPM r ...

Unable to establish connection to MongoHQ using Node.js connection URL

I have successfully set up and run a Node.js app using my local development MongoDB with the following settings and code: var MongoDB = require('mongodb').Db; var Server = require('mongodb').Server; var dbPort = 27017; v ...

Alert box in Vue.js

Embarking on my journey with VueJS. I previously implemented an alert box using jQuery. Now, I am attempting to recreate that in VueJS. Here is my current progress: 1- Developed a component named NovinAlert.vue which includes: <template> & ...

"An error message is displayed stating that the maximum call stack size has been exceeded while looping through an

Dealing with an array containing 10,000 items and attempting to assign a new property to each item has been a challenge for me. _async.mapLimit(collection, 100, function (row, cb){ row.type = "model"; cb(null, row); }, function (err, collect ...

What is the best way to prevent handleSubmit from triggering a re-render when moved to a different

Just started experimenting with React and ran into an issue that I can't seem to find a solution for anywhere. I have a basic search form that interacts with an API. If an invalid value is returned, it displays an H3 element with an error message lik ...

What is the reason that the index is consistently the final index when utilizing it to pass to a function while iterating over an array with map()?

Currently, I am utilizing the map function to iterate over an array object fetched from the server. Each object within the array is used to populate a row in a table for displaying data. I need to perform a specific action for each row by invoking a functi ...

Bug in Async.js causes unexpected results in loop involving numbers

When attempting to reference a variable in a for loop using the Async Library for Node.js, it seems to not work as expected. Here is an example: var functionArray = [] , x; for(x = 0; x < 5; x++) { functionArray.push(function (callback) { conso ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Migration processes encountering delays due to running nodes

When running migrations in Node, I am encountering a timeout error. The specific error message is: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. Here is the ...

Link the Sass variable to Vue props

When working on creating reusable components in Vue.js, I often utilize Sass variables for maintaining consistency in colors, sizes, and other styles. However, I recently encountered an issue with passing Sass variables using props in Vue.js. If I directly ...