Append new Item to a list in Vue 2
Solution 1
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 })
Solution 2
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.
Solution 3
If you're using lodash
, try this.
this.users.push(_.cloneDeep(this.user))
Comments
-
Hamed Kamrava almost 2 years
I have a very simple form which gets
name
andage
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?