The elements within the array are being refreshed accurately, however, a separate component is being removed

I have developed a component that has the ability to contain multiple Value components. Users can add as many values as they want, with the first value being mandatory and non-removable. When adding two new Value components, I provide input fields for name and description. An input event is emitted so that the parent component can store all values from the different components. Clicking on the remove button next to a value triggers a method in the parent component to remove it from the list of values. While the correct value gets removed from the updated list, the issue arises when it removes the last component instead of the intended one. The data in the list seems accurate but the created components do not reflect this properly, even retaining old values. I am having trouble pinpointing the mistake in my code.

ParentComponent

<div v-for="(component, index) in components" v-bind:key="index">
    <Value
        class="value"
        :valueIndex="index"
        v-model="components[index]"
        :id="'value_' + index"
        :isFirst="index === 0"
     ></Value>
</div>

export default {
    name: "Values",
    components: {
        Value
    },
    data() {
        return {
            components: [{
                name: "",
                description: ""
            }],
            componentsCount: 1
        }
    },
    methods: {
        addValue() {
            this.components.push({
                name: "",
                description: ""
            });
        },
        removeValue(valueIndex) {
            console.log(valueIndex);
            console.log(this.components[valueIndex]);
            this.components.splice(valueIndex, 1);
        }
    }

ValueComponent

<b-col md="4" sm="12">
     <input
         type="text"
         class="value-input"
         v-model="buffer.name"
         :name="'description_' + (this.valueIndex + 1)"
         :placeholder="'Description ' + (this.valueIndex + 1)"
         @input="$emit('input', buffer)"
     >
</b-col>
<b-col v-if="isFirst" md="8" sm="12">
    <input
        type="text"
        class="value-input"
        v-model="buffer.description"
        :name="'description_' + (this.valueIndex + 1)"
        :placeholder="'Description ' + (this.valueIndex + 1)"
        @input="$emit('input', buffer)"
    >
</b-col>
<b-col v-else md="8" sm="10">
    <b-row>
        <b-col sm="10">
             <input
                  type="text"
                  class="value-input"
                  v-model="buffer.description"
                  :name="'description_' + (this.valueIndex + 1)"
                  :placeholder="'Description ' + (this.valueIndex + 1)"
                  @input="$emit('input', buffer)"
             >
         </b-col>
         <b-col sm="2">
             <button class="garbage-button" @click="removeValue()">
                  <img src="../../assets/bin.svg">
             </button>
         </b-col>
     </b-row>
</b-col>

     export default {
            name: "Value",
            props: {
                valueIndex: {
                    type: Number,
                    required: true
                },
                isFirst: {
                    type: Boolean,
                    required: true
                }
            },
            data() {
                return {
                    buffer: Object.assign({}, this.value)
                }
            },
            methods: {
                removeValue() {
                    this.$parent.removeValue(this.valueIndex);
                }
            }
        }
    }

If more code is needed or if there are any clarifications required, please let me know.

Answer №1

In the past, I encountered a similar issue where positions were being mistakenly deleted due to confusion.

The solution that ultimately resolved this for me involved implementing unique identifiers. By utilizing uuidv4, I was able to successfully correct the problem. This tool generates distinctive keys that can be applied to your items for binding purposes.

Answer №2

This pertains to the concept of in-place-patch feature in Vue, where using the index as a key may not be effective. It is advised to use another unique key like an id, as mentioned in other responses. The issue arises when the value assigned to buffer in the child component is only done once, resulting in the value not being updated when changes occur. To resolve this, you can utilize the watch property and adjust the buffer accordingly when changes are made within your v-for loop:

props: {
  // ...
  value: {
    type: Object,
    default: () => {
      return {};
    }
  }
},
data() {
  return {
    buffer: Object.assign({}, this.value)
  };
},
watch: {
  value(val) {
    this.buffer = val;
  }
}

DEMO

It's important to note that although the correct item is being deleted, the value is not updating due to the way Vue interacts with v-for loops.

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

The content within the tab is currently being loaded

Incorporating jQuery UI tabs into my webpage, I encounter a delay of 5-6 seconds when clicking on a tab as it triggers an ajax call for preparing and displaying content. The screen stays idle during this time, leading to user confusion. I am seeking a sol ...

Unraveling TypeScript code expressions

I am seeking clarification on the meaning and practical application of this particular expression. ((identifier:string) => myFunction(identifier))('Hi') myFunction const myFunction = (str:string) => { console.log(str) } The output displ ...

Enhancing User Experience with React-Redux: Implementing Subcategory Visibility based on Main Category Selection

How can I implement action logic to show and hide elements based on user interaction with main categories? Currently, all subcategories are being displayed at once, but I want them to be shown only when a user clicks on the corresponding main category. For ...

Is Python being used to track NBA.com stats?

Does anyone have any advice on how to extract NBA.com "tracking" stats using a python script and display them in a simple table? I'm particularly struggling with this specific section of stats on the site. Accessing stats directly from NBA.com can be ...

What is the best way to transform an array of strings into a JSON object?

When navigating back to a list page, I want to make sure that the filter criteria are still retained. My solution involves using cookies, which are set when the form filter is submitted. In the list page's mounted hook, I retrieve the specific cookie ...

Utilizing JavaScript to dynamically update the user interface after submitting a form using jQuery

I am working on implementing an Input element that triggers a form submission: <input type="submit" value="Download" id="downloadButton" class="btn-download" /> The specific requirement is for the button to first execute a javascript function and t ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

Exploring the possibilities of combining Selenium Code and F# with Canopy

Currently, I am facing the challenge of incorporating Selenium code into my F# project while utilizing the canopy wrapper. Canopy relies on Selenium for certain functions. My main struggle lies in converting Selenium code from Java or C# to fit within an ...

TypeScript's type inference feature functions well in scenario one but encounters an error in a different situation

I recently tried out TypeScript's type inference feature, where we don't specify variable types like number, string, or boolean and let TypeScript figure it out during initialization or assignment. However, I encountered some confusion in its be ...

The transfer of information through HTTP

I have been exploring the inner workings of HTTP servers and clients to better understand how data is transmitted. Despite reading numerous articles on the topic, I still have some lingering questions that remain unanswered. I would like to walk through th ...

How can you establish a default value on a paper select in Polymer?

I have a paper-select element that I want to customize with a default value when the page loads or after a specific event occurs. <dom-module id="custom-paper-select"> <template> <paper-select id="select-input-1" multiple ...

What is the method for retrieving the data from an XMLHttpRequest response?

Is there a way to use jQuery to query the result of an XMLHttpRequest? For example, let's say I have this code snippet: $.get('somepage.htm', function(data) { console.log($("div.abc").text()); }); The issue is that $("div.abc").text() i ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

The AngularJS function invoked itself within the structure

When working with my form, I encountered a problem involving custom input directives and text fields. In addition to these elements, there are buttons: one for adding a new input to the form which is linked to the function $scope.AddNewItem() in the contro ...

The data type 'string[]' cannot be assigned to the data type '[{ original: string; }]'

I have encountered an issue while working on the extendedIngredients in my Recipe Interface. Initially, I tried changing it to string[] to align with the API call data structure and resolve the error. However, upon making this change: extendedIngredients: ...

Guide to parsing JSONP information using Express

I am attempting to transfer data from phonegap to an express application. Below is the code I am using: Phonegap: $.ajax({ type: 'POST', url:"http://127.0.0.1:3000/test", data: {"test":"this works!"}, dataTyp ...

Tips for invoking the href function in jwplayer with individual arguments

I need assistance with configuring jwplayer to load a list of href links one by one. Each href link includes a function that needs to be triggered automatically with specific parameters passed to JavaScript. Below is the code snippet I am currently worki ...

trouble with maintaining nodejs mariadb connection

Hello, I am working with nodejs to create a rest API However, I have encountered an issue Let's take a look at the code var http = require('http'); var url = require('url'); var mariadb = require('mariadb'); http.c ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...

Distribution running of VueJS doesn't show styles

Even though I am able to successfully run my Vuejs app using nom run serve, I am facing an issue when I build it and deploy it to nginx. None of my styles, especially bootstrap, are appearing. Despite my app logic appearing correct and all my js and css ...