Vue.js是否有内置方式将持久对象的副本添加到重复数组中 [英] Does Vue.js have a built in way to add a copy of a persistent object to a repeated array
问题描述
我有一个Vue.js应用程序,其中有一系列物品的V形重复.我想将newItem添加到项目列表.当我尝试this.items.push(this.newItem)
时,推送的对象仍然绑定到输入.请考虑以下内容:
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);
}
}
});
以上将按预期方式将绑定的对象推送到items数组.问题是我只想要对象的副本,这样当输入更改时它将不再更改.请参阅此此小提琴.我知道我可以做到:
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
})
}
这可行,但是重复很多.
问题:是否有一种内置的方式仅添加对象的副本而不是持久对象.
The question: Is there a built in way to add just a copy of the object instead of the persistent object.
推荐答案
请参见此问题在GitHub上.
See this issue on GitHub.
浅克隆
在使用 Evan You 之前,我一直使用jQuery的$.extend
,指出存在未记录的扩展功能Vue.util.extend
进行浅层克隆.因此,您可以使用的是:
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));
}
请参见更新的小提琴.
深层克隆
在引用其他对象的对象上进行浅表克隆时,请将引用复制到外部对象,而不是克隆它们.要完全克隆对象,请执行深度克隆.
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.
对于深层克隆,按照第一个链接中Evan的建议,可以使用:JSON.parse(JSON.stringify(object))
.可以在此小提琴和
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.
如果使用lodash,请检出 lodash cloneDeep .如果使用NPM,请检查克隆-深.
If using lodash check out lodash cloneDeep. If using NPM check out clone-deep.
这篇关于Vue.js是否有内置方式将持久对象的副本添加到重复数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!