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>