优化代码 for (let item of that.parentTemplate) { if (item.key == 'existContract') { if (!item.disabled || !Array.isArray(item.disabled)) { item.disabled = []; } if (e === 1) { item.disabled = item.disabled.filter((disabledItem) => disabledItem != index); } else if (e === 2 || e == undefined || e === '') { that.changeForm({ ['existContract' + more]: '', }); item.disabled.push(index); } else { item.disabled = item.disabled.filter((disabledItem) => disabledItem != index); } } if (item.key == 'contractCode') { if (!item.disabled || !Array.isArray(item.disabled)) { item.disabled = []; } if (e === 1) { } else if (e === 2 || e == undefined || e === '') { that.changeForm({ ['contractCode' + more]: '', }); item.disabled.push(index); } else { item.disabled = item.disabled.filter((disabledItem) => disabledItem != index); } } if (item.key == 'isProjectCost') { if (!item.disabled || !Array.isArray(item.disabled)) { item.disabled = []; } if (e === 1) { item.disabled = item.disabled.filter((disabledItem) => disabledItem != index); } else if (e === 2 || e == undefined || e === '') { that.changeForm({ ['isProjectCost' + more]: '', }); item.disabled.push(index); } else { item.disabled = item.disabled.filter((disabledItem) => disabledItem != index); } } }
时间: 2024-02-14 20:29:10 浏览: 82
omapfb-main.rar_If...
你可以尝试优化这段代码,减少重复的代码块。你可以使用一个数组来存储需要处理的字段名,然后使用循环来处理每个字段。
```javascript
const fields = ['existContract', 'contractCode', 'isProjectCost'];
for (let item of that.parentTemplate) {
for (let field of fields) {
if (item.key === field) {
if (!item.disabled || !Array.isArray(item.disabled)) {
item.disabled = [];
}
if (e === 1) {
item.disabled = item.disabled.filter((disabledItem) => disabledItem != index);
} else if (e === 2 || e == undefined || e === '') {
that.changeForm({
[field + more]: '',
});
item.disabled.push(index);
} else {
item.disabled = item.disabled.filter((disabledItem) => disabledItem != index);
}
}
}
}
```
通过引入一个 `fields` 数组,我们可以避免多次重复判断每个字段的 key。这样可以使代码更简洁,并且易于维护。
阅读全文