Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append new Item to a list in Vue 2

I have a very simple form which gets name and age from user and add this to a list.

You can check that on JSFiddle.

Here is HTML :

<div id="app">
<ul>
  <li v-for="user in users">{{ user.name +' '+ user.age }}</li>
</ul>
<hr>
  <form v-on:submit.prevent="addNewUser">
    <input v-model="user.name" />
    <input v-model="user.age" />
    <button type="submit">Add User</button>
  </form>
</div>

Here is Vue code:

new Vue({
   el: '#app',
   data: {
    users: [{name:"Mack", age:20}],
    user: {name:"", age:0}
   },
   methods: {
     addNewUser() {
        this.users.push(this.user);
     }
   }
});

The Problem

The problem is where I trying to add more than one user to the list. As you can see, when I type new value for the new user, previous values of recently added users change too!

How can I fix it?

like image 229
Hamed Kamrava Avatar asked Jul 19 '17 05:07

Hamed Kamrava


People also ask

How do I add items to my Vue list?

Render the Add Item button, and bind the click event. On the click event handler, pass data with random id to the addItem method to add a new list item on clicking the Add Item button.

How do I add elements to an array in Vue?

Add Element to Array With push() Method To add an element to an array in Vue, call the push() method in the array with the element as an argument. The push() method will add the element to the end of the array. Clicking the button adds a new fruit element.

How do I add components to Vue HTML?

The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.

Can you use Vue 2 components Vue 3?

There are a number of breaking changes from Vue 2 to 3. You won't be able to just use Vue 2 components in Vue 3 without accounting for these.


1 Answers

When you push this.user to the array you're pushing the reference to that data. Instead, create a new object using the data from the user object:

this.users.push({ name: this.user.name, age: this.user.age })
like image 151
Daniel D Avatar answered Oct 04 '22 00:10

Daniel D