Issue with Vue.js: Nested field array is triggering refresh with inaccurate information

I've been working on a Vue page where I want to have nested field collections, with a parent form and repeatable child forms.

Everything seems to be working fine except that when I try to delete one of the child forms, the template starts rendering incorrectly.

To see the issue in action, check out this fiddle example that I put together - https://jsfiddle.net/c4marcus/1mu2oceb/8/

In the sample data provided, there is basic information about The Beatles. If you click the trash can next to "Ringo," it mistakenly removes "George" instead of "Ringo."

However, upon submitting the form, the correct data is being saved (as shown in the screenshot below).

I suspect that the issue lies within the `MemberFormset` Vue component's `remove` method, which gets triggered when the trash can button is clicked.

remove: function(index) {
    this.members.splice(index, 1)
    this.$emit('input', this.members)
},

After splicing the data, the template should render the array of forms with the updated information.

<div class="form-group" v-for="(member, index) in members">
    <member-form :model="member"
                 :index="index"
                 @input="update(index, $event)">

        <div slot="trash">
            <button type="button"
                    class="btn btn-default margin-top-md"
                    @click="remove(index)">

                <i class="fa fa-trash"></i>
            </button>
        </div>

    </member-form>

    <hr v-if="separator(index)" />
</div>

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

Answer №1

It seems that the main problem lies here:

 <member-form :model="member"
              :index="index"
              @input="update(index, $event)">

To address this issue, you should assign a key to the custom component within your loop. Even though you are not directly iterating over the custom component, providing a key helps Vue determine its DOM updating strategy. To do so, I have added an id to each member object.

members: [
  {name: 'John', id: 1},
  {name: 'Ringo', id: 2},
  {name: 'Paul', id: 3},
  {name: 'George', id: 4}
]

Subsequently, the template has been adjusted as follows:

 <member-form :model="member"
              :index="index"
              @input="update(index, $event)"
              :key="member.id">

Additionally, it was noted in the comments that the add method requires an update to include a new id value.

add: function () {
  const newId = Math.max(this.members.map(m => m.id)) + 1
  this.members.push({name: null, id: newId})
},

As a result, your DOM is now effectively updated following a deletion.

You can view the revised fiddle here.

Upon reviewing some of the code, I noticed a few things that seem to align with certain Vue gotchas. For example, the following code snippet:

update: function(index, value) {
  this.members[index] = value
  this.$emit('input', this.members)
},

Looks like it may lead to Vue's array change detection caveat. While it may not be causing problems currently, it could potentially pose issues in the future.

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

Begin the input box with some text

Currently, I am trying to incorporate a form field that automatically adds "http://" when clicked or typed into by a user. Below is the code snippet I have been using: <script type="text/javascript"> var input = $( "#website" ); input.val( input ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

What is the best way to select a specific value from JSON (Webhook) Data?

I am looking for a way to extract and store a specific value from a JSON data into a variable. Specifically, I want to save the value of Name (John) in a variable like this: var name = "". I attempted using var name = data.Name but it is not wor ...

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

What is the correct way to generate an await expression by utilizing recast/esprima?

I have an issue with a JavaScript function export const cleanUp = async () => { await User.destroy({ where: {} }); }; I am attempting to add a line below await User.destroy({ where: {} }) using recast.parse(`await ${module}.destroy({ where: {} } ...

Can you provide a basic illustration of how routes are implemented in AngularJS?

After searching through numerous examples of using Routes with Angular, I have unfortunately not been able to find a working solution. Even the example provided in the official guide did not work properly (clicking on it resulted in a wrong URL that did no ...

*ngIf doesn't seem to be functioning as expected compared to other *ngIf directives

Encountering a peculiar issue with my *ngIf related to the isAdmin variable which determines whether the list of users in userList should be displayed or not. Strangely, it seems to behave differently compared to other *ngIf statements within the same comp ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

React-Troubleshooting list items and keys: A comprehensive guide to resolving common issues

I'm facing a challenge with generating unique key ID's for my list items. Even though I thought I had a good understanding of how unique keys function, it seems that I am mistaken. In the code snippet below, using key={index} or key={item} is no ...

The array value remains unchanged when included in the response

My goal is to send back the "projets" array within an expressJs route after fetching images for each item. However, when I return the response with the updated array, the newly added fields don't seem to be included. Note: When I log the added item, ...

Ajax request terminates once PHP has looped for a specific duration of time (2 minutes)

My challenge involves a button that is responsible for checking over 300 posts for a specific value and other conditions using about 20 if-else statements. Strangely, the ajax call initiated by this button halts after completing around 73 loops within a sp ...

What is the best way to retrieve seat number upon clicking in React Native?

I have implemented a for loop and assigned its value in the click function to retrieve the seat number when a seat is clicked. However, I am only getting the last number of the for loop every time a seat is clicked. Can someone guide me on how to obtain th ...

What is the best way to connect a string to a scoped variable in a view?

I'm looking to connect a string to a scope variable that will be determined by user input in an input field located within a specific view. The goal is for the combined string and scope variable value to appear in another div within the view. Here&ap ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

Incorporating live text into a tag while arranging items by price in both ascending and descending order

I recently added a button to my online shop that allows users to sort products by price, even though I don't fully understand the underlying JavaScript code. I want to enhance this button by updating the text to indicate whether the sorting order is ...

Utilizing ASP.NET with JavaScript to target elements by ID within an iframe

Struggling to populate my form within an iframe by inputting a value in a textbox and selecting an option from a dropdown menu. webform1 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title ...

Solution for Vue index.html Favicon problem

Having some trouble with my favicon.ico/png file in Vue 2.0 and Vue CLI 3.0. No matter what I try, it just won't work properly. I've located the problem to this specific issue. After running yarn build, the index.html file changes this line of ...

Ways to align images of the same size in a gallery using the margin: auto property

I have an image gallery within a div element named "container" with a specified width:70%. I need the images to be justified with auto margins. This is the HTML code I am using: (There are 4 images in total) <div class="container"> < ...

Transferring the data entered into an input field to a PHP script, in order to retrieve and display the value with JavaScript, unfortunately results in a

My situation involves a form that consists of only one input text field (search_term) and a submit button. The goal is to enter a keyword into the input field, click Submit, have the keyword sent to a php script for json encoding, and then returned back t ...