The easiest method is to completely reset the entire user
object instead of modifying it property by property:
add()
{
this.users.push(this.user);
this.user = {name: '', phone: ''};
}
Check out the demonstration below:
new Vue({
el: '#app',
data: {
user: {name: '', phone: ''},
users: []
},
methods: {
add() {
this.users.push(this.user);
this.user = {name: '', phone: ''};
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
name: <input type="text" v-model="user.name" /><br>
phone: <input type="text" v-model="user.phone" /><br>
<button @click="add">add user</button>
<hr>
users: {{ users }}
</div>
Why did it not work as expected?
When you use:
this.users.push( this.user );
// You are changing the name inside the users array
this.user.name = '';
By pushing this.user
into the this.users
array, any subsequent changes will affect the same object that is now in the array.
In contrast, by overwriting it, a new object is created:
this.users.push(this.user);
this.user = {name: '', phone: ''};
// The above line points `this.user` to a new object.
// Changes made to `this.user` after this point do not affect the previous object inside the array
// For example:
this.user.name = 'bob';
Alternative Approach: Cloning.
If you prefer cloning, there are a few options available. Starting with "manual" cloning:
new Vue({
el: '#app',
data: {
user: {name: '', phone: ''},
users: []
},
methods: {
add() {
this.users.push({name: this.user.name, phone: this.user.phone});
this.user.name = '';
this.user.phone = '';
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
name: <input type="text" v-model="user.name" /><br>
phone: <input type="text" v-model="user.phone" /><br>
<button @click="add">add user</button>
<hr>
users: {{ users }}
</div>
For deep cloning:
new Vue({
el: '#app',
data: {
user: {name: '', phone: ''},
users: []
},
methods: {
add() {
let userDeepClone = JSON.parse(JSON.stringify(this.user));
this.users.push(userDeepClone);
this.user.name = '';
this.user.phone = '';
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
name: <input type="text" v-model="user.name" /><br>
phone: <input type="text" v-model="user.phone" /><br>
<button @click="add">add user</button>
<hr>
users: {{ users }}
</div>
Lastly, for shallow cloning:
new Vue({
el: '#app',
data: {
user: {name: '', phone: ''},
users: []
},
methods: {
add() {
let userShallowClone = {...this.user}; // or Object.assign({}, this.user);
this.users.push(userShallowClone);
this.user.name = '';
this.user.phone = '';
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
name: <input type="text" v-model="user.name" /><br>
phone: <input type="text" v-model="user.phone" /><br>
<button @click="add">add user</button>
<hr>
users: {{ users }}
</div>