When an element is added to an array with a v-model, it may result in

Currently, I have a series of text input fields generated through a v-for loop with a v-model linked to an array. My goal is to incorporate new elements into the array, which in turn creates additional input fields.

While everything seems to be functioning correctly so far, there's an issue where the new input fields appear to be sharing the same index or some other anomaly that causes them to display identical values.

To better illustrate this problem, I've created this JSFiddle. If you click the button twice and proceed to edit one of the newly added input boxes, all the new input boxes will reflect the edited value. Ideally, only the modified input box should display the new value.

I suspect there might be something critical that I am overlooking here. Is there anyone willing to provide assistance with this issue?

Javascript:

new Vue({
  el: '#app',
  data: {
    items: [{name: "one", id: 0}],
    template: {
        name: "two",
        id: 2,
    },
  },
   methods: {
    addRow: function(){
    this.items.push(this.template);
    this.items[this.items.length - 1].id = Math.random();
    }
  }
  })

HTML:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <div v-for="(item,index) in items" :key="item.id">
  <input v-model="item.name">
  </div>
  <button v-on:click="addRow">
  Add row
  </button>
  <div>Array content: {{items}}</div>
</div>

Usage: Screenshot showing the current behavior

Answer №1

The issue arises when using array.push(declaredObject) as it only adds a reference of template, causing any changes to be reflected in all references.

To avoid this, you should add a new object with identical properties. This can be achieved through methods such as Object.assign({}, this.template) or the more recent technique known as Destructuring objects {...this.template}. In your specific scenario, use

this.items.push({...this.template})

Answer №2

give this a try:

this.items.push({
            name: "two",
             id: 2,
           });

Consider using this.items.push(this.template) because the template property is reactive and may impact other properties that rely on it

Take a look at this code snippet

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

Retrieve the class that corresponds to the element in the given list

In my JavaScript code, I have a NodeList of elements that were selected by querying multiple classes. I am using a "for" loop to iterate through the list. What I need is a concise one-liner to quickly determine which class each element was selected by so I ...

Is there a modal confirmation feature available in Salesforce?

if ((Modal.confirm && Modal.confirm('some unique text')) || (!Modal.confirm && window.confirm('same but different text'))) navigateToUrl('another link here','ANOTHER DETAIL','submit'); I am curious about t ...

Utilize JavaScript to assign a value to a concealed Pardot field

Recently, I've been working on setting a hidden Pardot field within an iframe. Oddly enough, when I manually input the query selector in my Chrome console, I successfully locate the element. However, when running this code snippet (embedded in the &l ...

What is the best way to execute a specific set of unit tests in Gulp-Angular using Karma?

In the midst of my AngularJS 1.4 project, fashioned through the Gulp-Angular yeoman generator, I find myself facing a dilemma. With karma and gulp settings already in place, executing gulp test runs all *.spec.js files within the project. However, my desir ...

Encountering a segmentation fault error, yet at a loss for how to resolve it

I am struggling with a code that is causing a segmentation fault, and debugging it has been challenging for me. It seems like my lack of knowledge in C syntax might be the reason behind this issue, even though I have already gone through TCPL. #include ...

Guide to removing a Firebase Storage directory using a Firebase Cloud Function?

I'm having trouble finding the deleteFiles() method and the DeleteFilesOptions argument in the Firebase API reference. My IDE is indicating that this method requires an optional argument, but I can't seem to locate any information on this type. I ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

What is the process for triggering a sorted output from my MongoDB database by simply clicking a button?

I'm struggling with sorting my collection by rating in my code. I have this snippet where I'm sending my collection to index.ejs: router.get('/', (req, res) =>{ FILM .find().limit(6) .then(films => res.render(& ...

The clearing of sessions is not supported by Node.js / Express.js

At the start, the application loads some users using Angularjs / $http.get(). As you scroll down, more users are loaded dynamically (infinite scroll). In addition to this, there are location filters on the page. Users can select a different Country and Ci ...

Saving Pictures in Database Without Using jQuery

Hey there fellow developers, I'm currently immersed in a web project that involves reconstructing a social media platform similar to snapchat. To capture images, I am utilizing my webcam with JavaScript and saving the image data to a variable named i ...

Debugging Windows Node.js applications remotely on Azure Web Apps or Azure Functions

I'm working with Windows-based Node.js applications deployed on Azure Web Apps or Azure Functions. It looks like the Visual Studio Code (VSC) extensions are intended for Linux environments only. What is the best way for me to debug these application ...

What is preventing the Date Picker in Selenium from accepting attribute values when using JavaScript for the Spice Jet application?

My implementation of JavaScript for the Date picker in Selenium is running successfully, however, the date is not being selected in the date picker. public class SpicJetBooking { static WebDriver driver; public static void main(String[] args) t ...

Dealing with bodyParser errors in Express.js

Whenever I try to upload an image that exceeds my 5mb limit, I get hit with a payload error. Is there a better way to handle payload errors, like sending JSON or HTML responses instead? PayloadTooLargeError: request entity too large at readStream (D:&b ...

Navigating Angular QueryList through loops

I am currently trying to gather all the images in my component and store them in an array. To achieve this, I am utilizing Angular's @ViewChildren which returns a QueryList of ElementRef: @ViewChildren('img', { read: ElementRef }) images: Q ...

troubles with variables in AngularJS Formly templates

Having trouble displaying model or other variables in my template? Check out this link for reference: http://jsbin.com/wofulinufo/edit?html,js,output. Question: What is the solution for displaying variables from controller? Even when I try using {{model} ...

Transforming a bezier curve into a flat surface in three.js

I am currently working on creating a curved road in three.js using bezier calculations. However, I am facing a challenge in converting the sequence of curved lines into a curved plane. Within my 3D scene, I have cars, a road made from a plane, and a path ...

Using ReactJS to compare arrays and render only if the name is present in both arrays

Currently, I am developing a Star Wars web application using ReactJS. The data is being retrieved from the SWAPI (an API that provides JSON data about Star Wars). While everything is functional, I want more control over which characters are displayed. At t ...

Obtaining PHP array via asynchronous JavaScript and XML (AJ

Having never done it before, I am trying to implement comments using AJAX. Despite hours of searching on Google, I find myself stuck and unsure if I am going about it the right way. My goal is to enable users to add a comment without having to reload the ...

Solving CORS policy errors in Dot Net Core Web API using Javascript

In my development environment, I am utilizing Visual Studio Code with liveserver for HTML and JavaScript, while also using Visual Studio 2019 for Dot Net Core Web API. I have set up the site in IIS on Windows 10 locally for the web API. My login functiona ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...