不用深拷贝实现this.dataSource.forEach((item) => { let editItem = cloneDeep(item) this.$set(this.editableData, item.key, editItem) })
时间: 2024-03-10 08:45:55 浏览: 17
如果不使用深拷贝,那么修改editItem对象的属性值也会影响到this.dataSource中对应元素的属性值。如果你确定不需要进行深拷贝,可以直接将item对象作为属性值添加到this.editableData对象中,如下所示:
```
this.dataSource.forEach((item) => {
this.$set(this.editableData, item.key, item)
})
```
这样就可以将this.dataSource中的每个元素以item.key作为属性名,添加到this.editableData对象中,而且不需要进行深拷贝。但是需要注意的是,如果你在修改this.editableData中的元素时,需要同时修改this.dataSource中对应元素的属性值,否则会导致数据不一致的问题。
相关问题
把这个事件合成一个 Edats() { this.dataSource.forEach((item) => { let editItem = cloneDeep(item) this.$set(this.editableData, item.key, editItem) }) this.dataSourceFeWate.forEach((item) => { let editItem = cloneDeep(item) this.$set(this.editableDataFeWate, item.key, editItem) }) this.conceal = true this.concealFeWater = true },
可以将这个事件重构为一个更通用的方法,如下所示:
```
editData(dataSource, editableData, conceal, dataSourceFeWate, editableDataFeWate, concealFeWater) {
dataSource.forEach((item) => {
let editItem = cloneDeep(item)
this.$set(editableData, item.key, editItem)
})
dataSourceFeWate.forEach((item) => {
let editItem = cloneDeep(item)
this.$set(editableDataFeWate, item.key, editItem)
})
conceal = true
concealFeWater = true
}
```
然后在需要调用的地方传入相应的参数即可:
```
this.editData(this.dataSource, this.editableData, this.conceal, this.dataSourceFeWate, this.editableDataFeWate, this.concealFeWater)
```
换一种方法实现deleteItem(key) { let dataSourceLength = this.dataSource.length; this.dataSource = this.dataSource.filter(item => item.key !== key); if (dataSourceLength === 1) { this.addItem(0); } this.dataSource.forEach((item, index) => { item.key = index; }); this.$delete(this.editableData, key); },
这段代码的作用是从数据源 `dataSource` 中删除指定 `key` 的项,并且删除 `editableData` 对象中对应的属性。如果数据源中只剩下一项,那么会自动添加一项。
这里提供一种使用 `splice` 方法的实现方法:
```
deleteItem(key) {
let index = this.dataSource.findIndex(item => item.key === key);
if (index !== -1) {
this.dataSource.splice(index, 1);
this.dataSource.forEach((item, index) => {
item.key = index;
});
}
this.$delete(this.editableData, key);
if (this.dataSource.length === 1) {
this.addItem(0);
}
}
```
这个实现方法首先通过 `findIndex` 方法找到要删除的项在数据源中的索引,然后使用 `splice` 方法将其从数组中删除。接着,更新数据源中的 `key` 属性值,并且从 `editableData` 对象中删除对应的属性。最后,如果数据源中只剩下一项,自动添加一项。