How to attach a custom event to a nested component in Vue.js when using a for loop

I have implemented a system using three single-file-components.

  • ParentVariation.vue
  • VariationInfo.vue
  • Childvariation.vue

In this setup, the variation-info child component emits a MarkedFilled event which is then caught by the ParentVariation component. Here's a snippet from the ParentVariation.vue file:

<template>
   // Content of ParentVariation.vue
</template>

<script>
    export default {
       // Script content
    }
</script>

In the main Vue instance, I have set up the initial data as follows:

data: function() {
    return {
        parents: [{ id:0, child: [], filled:'' }]
    }
},

The initialization of ParentVariation looks like this:

<parent-variation v-for="parent in parents" :row="parent" :key="parent.id"></parent-variation>

The goal here is to ensure that when the MarkedFilled event is triggered from the child component (variation-info), the parent component (parent-variation) should update the 'filled' property for the corresponding parent element on the main Vue instance. However, currently, only the first parent element's 'filled' property gets updated each time the event is called. The objective is to modify the property of the clicked element dynamically.

After spending two days on this issue, I am still unable to resolve it. Any assistance or insights would be highly appreciated. My primary aim is to understand why only the first element is getting affected every time this event occurs.

Answer №1

If you're looking to experiment, consider dispatching the markedFilled event to the parent component:

In ParentVariation.vue

<variation-info :filled="row.filled" @markedFilled="$emit('markedFilled')" :key="row.id">
</variation-info>

and in the main script

<parent-variation v-for="(parent, index) in parents" :row="parent" :key="parent.id" @markedFilled="changeFilled(index)">
</parent-variation>

export default {
  data: function() {
   return {
       parents: [{ id:0, child: [], filled:'' }]
   }
  },
  methods: {
    changeFilled(index) {
      this.parents[index].filled = true
      this.parents = JSON.parse(JSON.stringify(this.parents))
    }
  }
}

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

Deciphering JSON strings using JavaScript

Here is a string that I am trying to parse using Json: {\"description\": \"PSY - Gangnam Style (\\uac15\\ub0a8\\uc2a4\\ud0c0\\uc77c) \\n\\u25b6 NOW available on iTunes: h ...

Animate the sliding of divs using the JavaScript animation function

I've designed some boxes that function similar to notifications, but now I want to smoothly slide them in from the left instead of just fading in. I know that I need to use .animate rather than .fadeIn to achieve this effect. The code snippet I&apos ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...

An Ajax GET request will not be able to locate the JSON file

I am having issues retrieving Key and Values from a JSON file using the function provided. Despite placing the 'datafile.json' in the same directory, the code fails to execute the alert(weblink) function, while the alert('test 1') works ...

I am in the process of updating the Vuetify version from 1.5 to 2.0, however, the plugin that was previously installed is now missing from the project

Issues with displaying old Vuetify plugins, but new ones appear. The v-checkbox plugin is a specific example. Can someone provide assistance? The v-checkbox element is not visible **Old Vuetify Configuration Update to version 2.0:** // v2.0 // ...

What is the process of utilizing multiple npm registries within Yarn?

Currently, I am facing a challenge while setting up Yarn 0.17.9 in our environment due to issues with our registry setup. Our environment involves two registries - the official npmjs registry and our own internal network registry (Sinopia). The main issue ...

Step-by-Step Guide: Unveiling a Particular Modal Post-Submission of Form with

My website has a form inside a modal, and when the form is submitted, I don't want the modal to close. However, I have encountered an issue because my SQL UPDATE statement redirects to the same page after updating the database. This disrupts the funct ...

Issue with child component mounted before parent component creation

I have encountered an issue in my Vue application. It seems that the child component's mounted function is being executed before the parent component's created function. I am passing props from the parent component to the child component and I w ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

Check if the element is not present in the array, then add it to the array

I am attempting to generate an array in JavaScript with unique elements extracted from a JSON feed. My thought process is possibly too influenced by PHP, where a simple script like the one below would suffice: $uniqueArray = array(); foreach($array as $ke ...

Exploring the dissimilarity between the methods find() and filter().shift() in JavaScript

Recently, I made the decision to cut down on my use of underscore/lodash in some of my projects and found that browser support for the full functionality of the find method is lacking. What sets the ES6 method find apart from using .shift() with filter res ...

"Each time the header of the BS5 accordion is clicked, it van

While using the BS5 accordion, I noticed that it's behaving differently than described in the documentation. Whenever I click on the header, it disappears. <link href="//cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="style ...

Unable to display $children within a different component

Looking to make the content dynamic, I experimented with the following code snippet. When checking $children[0], the data appears correctly but does not display on the HTML page. Any ideas on how to render $children? Main: <template> <foo> ...

Converting and storing Canvas data as a blob, and then saving the blob as

There is a clickable icon on the page that triggers an action when clicked. Currently, the icon is set as an anchor tag. However, I want to change it to a div like all the other icons in my UI. But for some reason, the following code isn't working. W ...

Scrolling through a lengthy table without affecting the overall window scroll

I currently have a situation where I have a table positioned below several div elements: <div></div>...<div></div> <div id="tablecontent"> <table>...</table> </div> My goal is to make the table scrollable ...

Exploring Angular: Techniques for searching within nested arrays

I am looking for a function that can search and filter the largest value in a nested array, and then return the parent scope. Here is an example of my array: data = {"people": [{"male": [ {"name": "Bob" ,"age": "32"}, {"name":"Mike", "age ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Is there a way to obtain the coordinates of an SVG element by simply clicking on a specific point?

I'm still learning about SVG and I'm trying to trigger an event that captures the click coordinates when clicking on the SVG. I have a few questions: Since I'm using Angular, I'm unsure if it's possible to keep my function in th ...

No shadows are visible when using a collada model on a MeshPhongMaterial surface with a spotlight illuminating the scene

I have been trying to solve this issue for a long time but have been unsuccessful. I am attempting to add shadows to my .dea model using MeshPhongMaterial, but the shadows are not appearing. The camera is in the correct position, the ground is made of Mes ...

Developing an HTML table using information from JSON dataset

I am working with an HTML file that includes the following code snippet: <div> <table id="apps"></table> </div> Recently, I started receiving JSON data structured like this: { "1": [ { "A": "", ...