我正在尝试通过使用switch语句而不是if语句将这条条件代码转换为帮助函数,以最大程度地减少我当前在组件中拥有的代码量,我可能会对此加以改进。如何在新文件中执行此操作并将其导入到我的组件中?
import { USER_TYPES } from '../../constants/user';
const usertypeToName = {
1: 'client',
2: 'supportWorker',
3: 'accountManager',
};
if (this.$route.params.userType === usertypeToName[1]) {
return USER_TYPES.client;
}
if (this.$route.params.userType === usertypeToName[2]) {
return USER_TYPES.supportWorker;
}
if (this.$route.params.userType === usertypeToName[3]) {
return USER_TYPES.accountManager;
}
return 0;
usertypeToName
作为数组,然后使用find
import { USER_TYPES } from '../../constants/user';
const usertypeToName = ['client', 'supportWorker','accountManager']
// find key
const key = usertypeToName.find(v=> v === this.$route.params.userType)
// use dynamic property accessor
return key ? USER_TYPES[key] : 0