Tips for modifying the status of a single component within a v-for loop without impacting other components

I am encountering an issue with my childComponent that is dynamically rendered using v-for within the parentComponent. The Parent component contains logic to fetch data from the database and display it on the screen. The fetch request query is dependent on the selected child component. When a user clicks on a component, I want to indicate that the data is loading by changing the text inside the child component to loading. However, all child components generated by v-for display "Loading..." status when a request is sent, whereas I only want the clicked component to change.

Edit: Added CodeSandbox

I have created a simplified example of the problem.

parentComponent.vue

<template>
  <div>
    <childComponent
      v-for="(element, index) in 3"
      :key="index"
      :data="index"
      :loading="loading"
      @click-from-child="clickedEvent"
    />
    <p>{{ returnedData }}</p>
  </div>
</template>

<script>
import childComponent from "./childComponent";
export default {
  components: { childComponent },
  data() {
    return {
      loading: false,
      returnedData: "",
    };
  },
  methods: {
    clickedEvent(componentData) {
      this.loading = true;
      this.returnedData = "";
      console.log(`Request Sent to: ${componentData}`);
      setTimeout(() => {
        console.log("Request Completed - Success");
        this.returnedData = `Some Data returned from: ${componentData}`;
        this.loading = false;
      }, 3000);
    },
  },
};
</script>

childComponent.vue

<template>
  <p v-if="loading">LOADING...</p>
  <p v-else @click="triggerMethod">Click Me</p>
</template>

<script>
export default {
  props: {
    data: {
      type: Number,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    triggerMethod() {
      const customURL = `getDataURL/data=${this.data}`;
      this.$emit("click-from-child", customURL);
    },
  },
};
</script>

Answer №1

It's recommended to use the index as the loading prop instead of a boolean:

Vue.component('childComponent', {
  template: `
    <div>
      <p v-if="loading === data">LOADING...</p>
      <p v-else @click="triggerMethod">Click Me</p>
    </div> 
  `,
  props: {
    data: {
      type: Number,
    },
    loading: {
      type: Number,
      default: null,
    },
  },
  methods: {
    triggerMethod() {
      const customURL = `getDataURL/data=${this.data}`;
      this.$emit("click-from-child", customURL);
    },
  },
})
new Vue({
  el: "#demo",
  data() {
    return {
      loading: null,
      returnedData: "",
    };
  },
  methods: {
    clickedEvent(componentData) {
      this.loading = componentData;
      this.returnedData = "";
      console.log(`Request Sent to: ${componentData}`);
      setTimeout(() => {
        console.log("Request Completed - Success");
        this.returnedData = `Some Data returned from: ${componentData}`;
        this.loading = null;
      }, 3000);
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <child-component
      v-for="(element, index) in 3"
      :key="index"
      :data="index"
      :loading="loading"
      @click-from-child="clickedEvent(index)"
   ></child-component>
   <p>{{ returnedData }}</p>
</div>

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

A promise was caught with the following error: "Error in ./Search class Search - inline template:4:0 caused by: Maximum call stack size exceeded"

As a newcomer to Angular2, I am currently developing a web application that requires three separate calls to a REST API. To test these calls, I decided to simulate the API responses by creating three JSON files with the necessary data. However, my implemen ...

Tips for Properly Positioning Floating Pop-Up Messages Using CSS and jQuery

I was experimenting with adding a button that triggers a popup message to my website. I followed a coding tutorial using jQuery and CSS, which looks like this: Javascript : !function (v) { v.fn.floatingWhatsApp = function (e) {...} }(jQuery); CSS : .fl ...

Halting a function within a specific namespace

Is there a way to prevent certain characters from being entered during a keypress event for inputs when using a namespace in JavaScript? I noticed that even if the function returns false when the character is detected, the character still gets entered. How ...

Harmonizing Vue and JQuery compatibility

Is there full compatibility between Vue.js and JQuery? How about Vue.js and JQueryUI? I have experience using both frameworks without any issues in integration. Can anyone point out any potential conflicts that may arise? ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

What is the best way to execute a function before showing an alert in a $.post() callback?

Just to clarify, the code I'm working with is not original to me; I am simply making some interface adjustments using a plugin for an existing system. The task at hand involves creating a plugin that utilizes blockUI (yes, a plugin within a plugin) t ...

JavaScript encounters difficulty in reading the text file

I am working on a project where I need to read a local text file located at /home/myname/Desktop/iot/public/sensordata.txt using JavaScript when a button is clicked on a web page. Below is the code snippet I have been using: <html> <head> ...

Using an if statement following the iteration of a JSON object in a React Native application

I am currently working on a weather app using react native as a fun project. I have set up an API to fetch weather data in JSON format. My goal is to show the hourly weather details based on the current time of the day. export default class App extends ...

Tomcat hosting a dynamic duo: Spring Boot and React!

Exploring the world of Spring Boot application development with a React client using Gradle is an exciting journey for me as I navigate through these new technologies. My current progress includes successfully creating a WAR file that encompasses several i ...

Utilize vue.js input field to search for a specific username within a constantly updating list of users

I have created an input search functionality to filter a list of users using PHP. Now, I am attempting to implement the same filtering feature in Vue.js so that when a user searches for a name, the filtered user will be displayed in the list. Below is the ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...

Interested in learning how to filter nested tables?

After successfully integrating a filter code snippet, I encountered an issue with the filter not recognizing data tables that can only be inserted as nested tables. Due to my limited knowledge of JavaScript/CSS, I'm unsure if this problem can be resol ...

Using NUXT to dynamically pass object data into pages based on their path

Just starting out with Vue and Nuxt so please bear with me if this is a basic question. I have my routes generated dynamically by calling an API for my data in Index.vue. One API call fetches all the necessary data, stored in deals_array, so I don't ...

Techniques for Sending Data to Child Components in Vue.js

As a newcomer to Vue.js, I am attempting to pass a value to a child component within the framework. The HTML structure is as follows: <div id="example"> <my-component v-bind:data="parentData"></my-component> </div> To achieve ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

Understanding the mechanism of callback function in NodeJS within the context of routes and controllers

Trying to grasp the concept of callbacks and puzzled by the recurring issue TypeError: callback is not a function Here's my router setup: // getPriceRouter.js router.post('/getPrice', function(req, res) { priceController.getPrice(req, ...

Error: Vue.js application requires the "original" argument to be a Function type

I am facing an issue when trying to call a soap webservice using the 'soap' module in my Vue SPA. Strangely, I encounter an error just by importing the module. Despite my extensive search efforts, I have not been able to find a solution yet. Her ...

Having trouble closing the phonegap application using the Back Button on an Android device

I've encountered an issue with my code for exiting the application. It works perfectly the first time, but if I navigate to other screens and then return to the screen where I want to close the app, it doesn't work. <script type="text/javascr ...

Caution: Updating a component is not possible during the rendering of another component. ReactJS

I am encountering an error in my ReactHooks/Typescript application with a Navigation component that renders a PatientInfo component. The PatientInfo component is conditionally rendered based on the props it receives, determined by a searchbox in another ch ...