I have a Vue.js app where I have a v-repeat on an array of items. I want to add a newItem to the list of items. When I try this.items.push(this.newItem)
the obj
The top answer is wrong. Vue.util.extend has nothing to do with jQuery's extend. It's always a shallow clone. https://github.com/vuejs/vue/issues/1849#issuecomment-158770874
Object.assign and Spread operator are also shallow copy. see this https://scotch.io/bar-talk/copying-objects-in-javascript
Simply use the implementation of Ramda.js https://github.com/ramda/ramda/blob/v0.26.1/source/internal/_clone.js
_curry is not necessary if you don't want them.
Or check this MVA What is the most efficient way to deep clone an object in JavaScript?
This didn't work for me (vue 1.0.13). I used the following to create a copy without the data bindings:
this.items.push( JSON.parse( JSON.stringify( newItem ) ) );
You can use Vanilla JavaScript with Object.assign():
addItem: function(e) {
e.preventDefault();
this.items.push(Object.assign({}, this.newItem));
}
UPDATE:
You can also use Object Spread:
addItem: function(e) {
e.preventDefault();
this.items.push({...this.newItem});
}
See this issue on GitHub.
Shallow Clone
I was using jQuery's $.extend
until Evan You pointed out there is an undocumented built it extend function Vue.util.extend
that does a shallow clone. So what you could use is:
addItem: function(e) {
e.preventDefault();
this.items.push(Vue.util.extend({}, this.newItem));
}
See the updated Fiddle.
Deep Clone
When doing a shallow clone on an object that references other objects you copy the references to the external objects instead of cloning them. To clone the object completely do a Deep Clone.
For the deep clone, per Evan's suggestion in the first link, one could use: JSON.parse(JSON.stringify(object))
. This can be seen between this fiddle and this fiddle.
If using lodash check out lodash cloneDeep. If using NPM check out clone-deep.