我的代码有问题我有一组按 waste_id 分组的对象。现在,当我将新项目添加到现有 invoice_id 行时,一切正常。但是当我需要创建新 key (id 为新的 invoice_id)时,它会创建像 [(...)] 这样的数组而不是这个 (...)。两者都是数组,但之前的对象(我从数据库中获取它们并将它们分组在 laravell 中,然后用 json 发送)看起来像这样(...)。有什么不同?
addReceipts() {
$('.mass-checkbox__checkbox .custom-control-input').each((index, checkbox) => {
let thisComponent = this;
if ($(checkbox)[0].checked === true) {
if (this.invoice.allReceipts[thisComponent.gridReceiptItems[index].waste_type_id] !== undefined) {
if (this.invoice.allReceipts[thisComponent.gridReceiptItems[index].waste_type_id].some(function(obj) {
return obj.id === thisComponent.gridReceiptItems[index].id;
})) {
console.log("exist");
return;
} else {
console.log("no exist");
thisComponent.gridReceiptItems[index].deal_name = this.invoice.transport_names[thisComponent.gridReceiptItems[index].deal_id];
thisComponent.gridReceiptItems[index]._rowVariant = "warning";
this.invoice.allReceipts[thisComponent.gridReceiptItems[index].waste_type_id].push(thisComponent.gridReceiptItems[index]);
}
} else {
//problem starts here when i try create new arry
console.log("New!");
this.invoice.allReceipts[thisComponent.gridReceiptItems[index].waste_type_id] = new Array();
this.invoice.allReceipts[thisComponent.gridReceiptItems[index].waste_type_id].push(thisComponent.gridReceiptItems[index]);
}
console.log("Invoice:");
console.log(this.invoice);
}
});
},
---------------- 相同:
所以主要问题是 Vue 不会显示/更新第三项(新的一项)。为什么?
最佳答案
您正在直接设置/分配 Vue 的 react 机制无法检测到的数组元素。你应该使用 allReceipts.splice(idx, 1, newValue)
如果它是一个数组或者 this.$set(allReceipts, key, newValue)
如果它是一个对象.
另请查看 https://v2.vuejs.org/v2/guide/list.html#Array-Change-Detection尤其是在 https://v2.vuejs.org/v2/guide/list.html#Caveats
关于javascript - 为什么在创建空数组时 Javascript 在输出中显示 [(...)] 而不是 (...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57196862/