Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  199] [ 2]  / answers: 1 / hits: 59696  / 9 Years ago, mon, june 1, 2015, 12:00:00

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 object pushed is still bound to the input. Consider the below:



new Vue({
el: '#demo',

data: {
items: [
{
start: '12:15',
end: '13:15',
name: 'Whatch Vue.js Laracast',
description: 'Watched the Laracast series on Vue.js',
tags: ['learning', 'Vue.js', 'Laracast', 'PHP'],
note: Vue.js is really awesome. Thanks Evan You!!!
},
{
start: '13:15',
end: '13:30',
name: Rubik's Cube,
description: Play with my Rubik's Cube,
tags: ['Logic', 'Puzzle', Rubik's Cube],
note: Learned a new algorithm.
}
],
newItem: {start: '', end: '', name: '', description: '', tags: '', note: ''}
},

methods: {
addItem: function(e) {
e.preventDefault();

this.items.push(this.newItem);
}
}
});


The above will, as expected, push the object that is bound onto the items array. The problem is I want just a copy of the object so it will no longer change when the input changes. See this this fiddle. I know I can do:



addItem: function(e) {
e.preventDefault();
this.items.push({
name: this.newItem.name,
start: this.newItem.start,
end: this.newItem.end,
description: this.newItem.description,
tags: this.newItem.tags,
notes: this.newItem.notes
})
}


This works but is a lot of repetition.



The question: Is there a built in way to add just a copy of the object instead of the persistent object.


More From » vue.js

 Answers
31

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.


[#66382] Friday, May 29, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josh

Total Points: 391
Total Questions: 112
Total Answers: 90

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
josh questions
Wed, Aug 4, 21, 00:00, 3 Years ago
Mon, Aug 24, 20, 00:00, 4 Years ago
Wed, Aug 12, 20, 00:00, 4 Years ago
;