Components are mysteriously sharing props with each other

In my Vue component, I am encountering an issue when passing two different arrays to separate instances of the same component and then using v-for to send a single item from each array to another component via props. The problem arises when I inspect the prop in the final component, as it seems to retain the value from the previous array rather than the intended one.

Scenario:

<co-notifications class-name="writable" nots="{{ $notifications[0] }}"></co-notifications>

<co-notifications class-name="writable extended" nots="{{ $notifications[1] }}"></co-notifications>

CoNotifications Component:

<template>
<div>
    <div v-for="notification in notifications">
        <co-notification-item :class-name="className" :not="notification"></co-notification-item>
    </div>
</div>
</template>

    <script>
    import notificationComponent from './NotificationComponent.vue';

    export default {
        props: ['className', 'nots'],
        components: {
            'co-notification-item': notificationComponent
        },
        computed: {
            notifications(){
                return JSON.parse(this.nots)
            }
        },
    }
</script>

CoNotificationItem Component:

<template>
<div :class="['tableItem', className]">
    <div class="textareaWrapper">
        <input type="text" class="form-control" placeholder="Title" v-model="notification.title" v-if="notification.type === 'main'">
        <textarea class="form-control" rows="6" placeholder="Some text..."
                  v-model="notification.text"></textarea>
    </div>
    <div class="buttonWrapper">
        <button type="button" class="btn btn-success" @click="updateNotification"><i
                class="fe fe-check mr-2"></i>Save
        </button>
        <button type="button" class="btn btn-danger" @click="deleteNotification"><i
                class="fe fe-check mr-2"></i>Delete
        </button>
    </div>
</div>
</template>


    <script>
    import notificationComponent from './NotificationComponent.vue';
    export default {
        props: ['className', 'not'],
        components:{
            'co-notification-item': notificationComponent
        },
        data(){
           return {
               notification: this.not
           }
        },
        methods: {
            updateNotification(){
            this.notification.text = "test";

            },
            deleteNotification(){


            }
        }
    }
</script>

When reviewing the data in the arrays, there are 2 items in arr(0) and 2 items in arr(1). Upon inspecting the FIRST notifications with Vue tools, the information is shown correctly (CORRECT)

https://i.sstatic.net/eXuGa.png

However, when checking the other notifications reading from arr(1), the values are mixed up (INCORRECT)

https://i.sstatic.net/jfs69.png

I attempted using computed properties for CoNotification, which resolved the issue partially. However, it prevented me from binding v-model in CoNotificationItem since I needed the data() method. How can I ensure that the notification in CoNotificationItem matches the not variable while being accessible in data()? Why are conflicting values present?

Despite trying computed, watch, created, and mounted, I have been struggling with this issue for hours. Extensive research has been done including official documentation and online queries.

Some references I explored:

Vue.js passing props to data

Passing data from Props to data in vue.js

https://forum.vuejs.org/t/update-data-when-prop-changes-data-derived-from-prop/1517

Answer №1

To resolve the issue, make sure to include a unique key property for each item in a v-for loop.

<div v-for="notification in notifications" :key="someUniqueKey">
    <co-notification-item :class-name="className" :not="notification"></co-notification-item>
</div>

When using Vue, it is important to assign a unique identifier as the key property for each item in order to differentiate them. This helps Vue accurately track and manage elements without re-using props and data.

If you need further clarification or documentation references, feel free to comment or provide an additional answer. I am willing to edit or delete my response accordingly.

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

Can an inner promise in JavaScript not be caught by another promise?

When using promises, I am encountering an issue where the "catch" doesn't seem to catch its child promises. This results in me having to include two instances of the "catch" block. Facility.userHaveAccess(locationObject.created_by, locationObject.fac ...

What sets apart `Object.merge(...)` from `Object.append(...)` in MooTools?

This question may seem simple at first glance, but upon further inspection, the MooTools documentation for the 'append' and 'merge' methods appears to be identical. Here is the code snippet provided in the documentation: var firstObj ...

Exploring nested collections in Laravel 5.2

I'm currently working on a Laravel 5.2 application and facing an issue with extracting a nested collection from the parent collection. My goal is to retrieve all posts from the users that I am following using the following approach: $posts = \Au ...

Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player. Due to the structur ...

What is the best way to update the value of the nearest input field?

I am working with a table that has multiple rows, all structured in the same way. I have created a DIV element that can be clicked. When a user clicks on the DIV, I want the value of the input field in the same row to change. However, with the current co ...

Ways to determine if a textbox is empty and trigger a popup notification with jQuery

I'm having trouble with checking if the textbox is empty in my form. Every time I try to submit, instead of receiving an alert message saying "Firstname is empty," I get a message that says "Please fill out filled." ('#submit').click(func ...

Struggling to conceal the elusive x button that resets the input field

There is an X box that always appears, which I use to clear the text. However, I would like this X box to only appear when the input has focus and then hide after a word has been entered. Currently, it is visible all the time. https://i.sstatic.net/6Owwi. ...

Develop a worldwide computed attribute within a plugin on Vue 3

I'm attempting to establish a universal computed property within a Vue 3 plugin in order for my property to be utilized reactively across any component. I am adhering to the standard Vue 3 pattern: app.config.globalProperties.$foo = ... This method a ...

No code is appearing on the page, just a blank space

Whenever I visit this page on the web, the screen shows up as empty and I've encountered similar issues with other JavaScript pages that I've created. This makes me wonder if there might be a missing piece of code or something else causing the pr ...

I am in the process of extracting information from the database, but I encountered an error stating that the variable $request is undefined

My controller contains a method called request, which retrieves data from the database and then compacts the variable with the view. <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use ...

Unable to initiate beforeDraw using Vue-Chartjs (or any similar plugins)

I'm currently attempting to customize the text displayed on my Chartjs chart using vue-chartjs. My research suggests that I should utilize a beforeDraw plugin to achieve this. I have added the plugin to the options.plugins section, but it does not see ...

Generating an array within the custom hook results in the value being re-rendered with each change in state

While working on a custom hook in react native, I ran into an issue with the combination of useEffect and useState that led to an infinite loop. To demonstrate the problem, I created a small snack: import React, { useEffect, useState, useMemo } from &apos ...

Leveraging Vue mixin within a @Component

After implementing the vue-property-decorator package, I encountered an issue when trying to use a mixin method inside the beforeRouteEnter hook. Here is what I initially tried: import { Component, Mixins } from 'vue-property-decorator'; import ...

Ways to retrieve data from a URL and pass it to JavaScript code

I am currently experiencing difficulties in obtaining the values from an object requested through a link on my website. The issue arises from the fact that I have created a PHP method to retrieve data from the database for the values of a particular objec ...

Launch the file explorer using JavaScript/HTML

Is there a way to launch a real explorer window instead of the browser's directory look? For example, like the windows key + e window... Is there a method using html or JavaScript? I've noticed it in a Firefox add-on called new tab king, but I c ...

Error encountered while reIndex() function was being executed in PHP Client for OpenSearch operation

Currently, I have an Amazon OpenSearch Service configured. Within my Laravel PHP service, I am utilizing version 7.17.2 of the "elasticsearch/elasticsearch" client to establish a connection. Although I am aware that this client may not be the ide ...

Unexpected behavior when using Async.map in conjunction with async.waterfall

Utilizing Async, I am using async.map() to connect my data array with a function and incorporating async.waterfall() within that function to execute functions in a series. However, the waterfall function is not functioning as anticipated. I have also attem ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

Unexpected behavior: Vue toast from Bootstrap disappears instantly

My attempt to show a toast message has been unsuccessful. Despite trying all the example codes provided on https://getbootstrap.com/docs/5.1/components/toasts/, when I click the button to display the toast, it appears briefly and then disappears immediatel ...