簡體   English   中英

如何將此代碼轉換為幫助程序 function?

[英]How can i turn this code into a helper function?

我正在嘗試將這段可能通過使用 switch 語句而不是 if 語句來改進的條件代碼轉換為幫助程序 function 以最小化我當前在組件中擁有的代碼量。 如何在新文件中執行此操作並將其導入到我的組件中?

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

這是你想要的?

## util.js

import { USER_TYPES } from '../../constants/user';

const userTypeMap = {
  client: USER_TYPES.client,
  supportWorker: USER_TYPES.supportWorker,
  accountManager: USER_TYPES.accountManager,
};

export function mapUserType(name) {
  // Fallback to 0 incase mapping does not exist
  return userTypeMap[name] || 0
}


## component.js

import { mapUserType } from './util.js'

const userType = mapUserType(this.$route.params.userType)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM