如何添加新数据时覆盖数组已有元素,保持数组仅含一项?
解决方案
问题出在你用了push方法往数组里追加元素,这会导致每次点击都新增一项。要实现点击新项时直接替换数组内原有元素,只需要把push操作改成直接将数组赋值为包含当前新元素的数组即可。
修改代码中unitService.getFullUnitInformationForCopyUnitFunctionality的回调部分:
unitService.getFullUnitInformationForCopyUnitFunctionality(newValue.id).then(result => { // 直接赋值为仅包含当前元素的数组,覆盖原有内容 this.fullSelectedCar = [{ fullCarNumber: `${this.properties.find(owner => owner.id === result.data.ownerId).ownerNumber}-${result.data.carNumber}`, selectedSource: false, selectedDestination: false, ...result.data }]; }),
补充说明
如果你的业务场景需要先清空数组再添加(比如数组有其他关联操作),也可以用以下写法,效果完全一致:
unitService.getFullUnitInformationForCopyUnitFunctionality(newValue.id).then(result => { // 先清空数组 this.fullSelectedCar.length = 0; // 再添加新元素 this.fullSelectedCar.push({ fullCarNumber: `${this.properties.find(owner => owner.id === result.data.ownerId).ownerNumber}-${result.data.carNumber}`, selectedSource: false, selectedDestination: false, ...result.data }); }),
这两种方式都能保证fullSelectedCar数组始终只有当前点击的那一个元素。
内容的提问来源于stack exchange,提问作者Maflec
相关产品推荐
相关产品推荐

