Dut*_*IFF 21 javascript vue.js
我有一个Vue.js应用程序,我对一系列项目进行了v-repeat.我想将newItem添加到项目列表中.当我尝试this.items.push(this.newItem)推送的对象仍然绑定到输入.考虑以下内容:
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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,上面将推送绑定到items数组的对象.问题是我只想要一个对象的副本,以便在输入更改时它不再更改.看到这个小提琴.我知道我能做到:
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
})
}
Run Code Online (Sandbox Code Playgroud)
这有效但很多重复.
问题:是否有内置方法只添加对象的副本而不是持久对象.
Dut*_*IFF 39
在GitHub上看到这个问题.我正在使用jQuery,$.extend直到Evan You指出有一个未记录的内置扩展函数Vue.util.extend,相当于jQuery的扩展,深度设置为true.所以你将使用的是:
addItem: function(e) {
e.preventDefault();
this.items.push(Vue.util.extend({}, this.newItem));
}
Run Code Online (Sandbox Code Playgroud)
查看更新的小提琴.
小智 8
这对我不起作用(vue 1.0.13).我使用以下内容创建没有数据绑定的副本:
this.items.push( JSON.parse( JSON.stringify( newItem ) ) );
Run Code Online (Sandbox Code Playgroud)
您可以将Vanilla JavaScript与Object.assign()结合使用:
addItem: function(e) {
e.preventDefault();
this.items.push(Object.assign({}, this.newItem));
}
Run Code Online (Sandbox Code Playgroud)
更新:
您还可以使用对象传播:
addItem: function(e) {
e.preventDefault();
this.items.push({...this.newItem});
}
Run Code Online (Sandbox Code Playgroud)