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?
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.
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.
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.
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.
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With