[英]How should i go when adding an object to an array using javascript and vue?
抱歉,如果這是一個非常簡單的問題,我嘗試按照此處的一些答案進行操作,但我無法進行..
我想基於第一個對象向數組添加一個NEW對象
我發現可行的方式是這樣的:
new Vue({
el: "#app",
data: {
name: '', //name isnt inside and object
//failedExample: {name: ''}
array: []
},
methods: {
add(){
this.array.push({name: this.name}) // i push a key:value
//this.array.push(failedExample) // what i wished to do
}
}
});
https://jsfiddle.net/myrgato/6mvx0y1a/
我知道,通過使用帶注釋的array.push,我將一遍又一遍地向對象添加相同的引用,因此當我更改failExample.name的值時,它將在數組的所有位置發生變化。 有沒有辦法做到這一點? 像,我添加第一個對象,然后添加下一個對象作為新對象而不是引用?
它應該可以像您對“ failedExample”所做的那樣工作。 我看到的唯一錯誤是您在推入數組時忘記了this關鍵字。
所以試試這個:
new Vue({
el: "#app",
data: {
failedExample: { name: 'test'},
array: []
},
methods: {
add(){
this.array.push(this.failedExample);
console.log(this.array);
}
}
});
更新 :如果您想每次添加一個新對象,請嘗試克隆它,這樣就不會出現引用問題:
this.array.push(Object.assign({}, this.failedExample));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.