I have an array and an object that contains models.
I want to add the object to the array with the function push()
, but doing so changes all existing values in the array referring to the object.
Example of my code
var app = new Vue({
el: '#app',
data: function () {
return {
dato: {
nombre: '',
apellido: ''
},
array: []
}
},
methods: {
add: function() {
this.array.push(this.dato)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.6/vue.min.js"></script>
<div id="app">
<input type="text" placeholder="Nombre" v-model="dato.nombre" />
<input type="text" placeholder="Apellido" v-model="dato.apellido" />
<button v-on:click="add">PUSH</button>
<ul>
<li v-for="n in array">
{{ n }}
</li>
</ul>
</div>
It would be great if someone knows how to make the fix
estático
You could just
copiar
the object and save the copy in the array.For this you could use
Object.assign()
demonstration: