当我们在 vue 项目中可能出现以下场景:
javascript
export enum OperationEnum {
'详情' = 1,
'分配' = 2,
'邀请入驻' = 3,
'合同签约' = 4,
'撤销签约' = 5,
'申请上线' = 6,
}
javascript
const operation = (param) => {
if (param.operationType === OperationEnum.详情) {
routeDetailDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
}
if (param.operationType === OperationEnum.分配) {
routeOperationDialogRef.value.openDialog({
clueId: param.rowId.row.clueId,
dialogType: param.rowId.type,
});
}
if (param.operationType === OperationEnum.邀请入驻) {
inviteSettleDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
}
if (param.operationType === OperationEnum.合同签约) {
contractSignDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
}
if (param.operationType === OperationEnum.撤销签约) {
revokeContractDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
}
if (param.operationType === OperationEnum.申请上线) {
confirmOnlineDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
}
};
存在一个对应的枚举值,一个根据传入参数执行的函数,大量的 if 判断让代码变得很繁琐,也不利于后期维护。
有一个简单的处理方法如下:
javascript
const operation = (param) => {
const HandleMap = {
[OperationEnum.详情]: {
callback: () => {
routeDetailDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
},
},
[OperationEnum.分配]: {
callback: () => {
routeOperationDialogRef.value.openDialog({
clueId: param.rowId.row.clueId,
dialogType: param.rowId.type,
});
},
},
[OperationEnum.邀请入驻]: {
callback: () => {
inviteSettleDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
},
},
[OperationEnum.合同签约]: {
callback: () => {
contractSignDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
},
},
[OperationEnum.撤销签约]: {
callback: () => {
revokeContractDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
},
},
[OperationEnum.申请上线]: {
callback: () => {
confirmOnlineDialogRef.value.openDialog({
clueId: param.rowId.clueId,
});
},
},
};
const target = HandleMap[param.operationType];
target?.callback();
};
修改后的代码,更加方便后期维护,如果有更多的枚举值,继续往下写就好。之后遇到类似的代码都可以使用该方法进行完善。