现在有个问题在按下新增民用表具按钮后再按下取消后依然会保存这一行的数据
时间: 2024-12-15 08:24:46 浏览: 9
在当前实现中,当您点击“添加民用表具”按钮时,会向表格中新增一行并设为可编辑状态。如果之后点击了“取消”,该行应被撤销并且不应该保留数据。然而从代码来看,“取消”功能确实会调用 `cancel` 方法,但并没有完全清除新添加的数据。这可能是由于状态管理的问题。
以下是优化建议:
1. **修改 `cancel` 方法**:确保在取消编辑后不仅移除当前行的 `editable` 标记,还要将其从数据源中彻底删除。
```javascript
methods: {
// 其他方法...
cancel(key) {
const newData = this.data.filter(item => item.key !== key);
this.data = newData;
this.cacheData = newData.map(item => ({ ...item }));
this.editingKey = '';
this.$forceUpdate();
}
}
```
2. **调整 `cacheData` 管理**:在 `AddTable` 方法中将新的记录先存储在一个临时变量中,只有当确认保存时再将其加入到 `data` 和 `cacheData` 中。
```javascript
methods: {
// 其他方法...
AddTable() {
const newRecord = {
key: this.uniqueKeyGenerator(),
meterNum: '',
gmType2: '',
vendorCode: '',
meterNum1: '',
batch: '',
productionDate: '',
validityYears: '',
iccid: '',
imei: '',
statu: '',
depart: '',
departDate: '',
intakeDirection: '',
ware1house: '',
gauge: '',
minFlow: '',
maxFlow: '',
maxWorkPressure: '',
workVoltage: '',
editable: true
};
// 存储在临时变量中
this.tempNewRecords = [...this.tempNewRecords, newRecord];
this.data = [...this.data, newRecord];
this.cacheData = [...this.cacheData, {...newRecord}];
this.editingKey = newRecord.key;
},
cancel(key) {
const newData = this.data.filter(item => item.key !== key);
this.data = newData;
this.cacheData = newData.map(item => ({ ...item }));
// 移除未保存的新记录
this.tempNewRecords = this.tempNewRecords.filter(record => record.key !== key);
this.editingKey = '';
this.$forceUpdate();
},
save(key) {
const target = this.data.find(item => item.key === key);
if (target) {
delete target.editable;
// 将临时记录移至正式数据
const tempRecord = this.tempNewRecords.find(record => record.key === key);
if (tempRecord) {
this.cacheData = [...this.cacheData, tempRecord];
this.tempNewRecords = this.tempNewRecords.filter(record => record.key !== key);
}
this.data = [...this.data, {...target}];
this.cacheData = [...this.cacheData, {...target}];
}
this.editingKey = '';
this.$forceUpdate();
}
}
```
通过上述修改,可以确保在用户点击“取消”按钮时,新添加的行不会保留在数据中,从而避免数据残留的问题。
阅读全文