Hamed Kamrava
Hamed Kamrava

Reputation: 12847

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?

Upvotes: 6

Views: 30715

Answers (3)

wegelagerer
wegelagerer

Reputation: 3710

You should be creating a new object which should be decoupled from the data.

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

        this.users.push(newUser);
     }
   }
});

One more thing I'd suggest; I see that you are interpolating the value of the name and age by writing {{ user.name +' '+ user.age }} while instead you could convert that into a computed property and make it more reusable.

Upvotes: 8

Ikbel
Ikbel

Reputation: 7851

If you're using lodash, try this.

this.users.push(_.cloneDeep(this.user))

Upvotes: 2

Daniel D
Daniel D

Reputation: 998

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 })

Upvotes: 19

Related Questions