前言:项目中经常有不同字段显示不通过状态内容的需求,多数是采用if判断的形式,最好是将其写成对象的形式,既美观有可以减少判断的高频使用。
实例1:基础的一对一字段判断
//原始if形式
export function formatFood(type) {
if (type == 'SG') {
return '水果';
} else if (type == 'RL') {
return '肉类';
} else if (type == 'SC') {
return '蔬菜';
} else if (type == 'GL') {
return '谷类';
} else {
return '其他';
}
}
//对象形式
export function formatYDLX(type) {
return {
SG: '水果',
RL: '肉类',
SC: '蔬菜',
GL: '谷类'
}[type] || '其他'
}
实例2. 数量不多的多对一判断
export function formatFood(type) {
if (type == 'PG' || type == 'TZ' || type == 'XJ' || type == 'XG' || type == 'LZ' || type == 'TG') {
return '水果';
} else if (type == 'RL') {
return '肉类';
} else if (type == 'SC') {
return '蔬菜';
} else if (type == 'GL') {
return '谷类';
}
}
//修改后
export function formatFood(type) {
const fruit = ['PG','TZ','XJ','XG', 'LZ', 'TG'].includes(type) ? '水果' : '';
return {
RL: '肉类',
SC: '蔬菜',
GL: '谷类'
}[type] || fruit
}
实例3. 数量多的多对一判断,建议单独建一个文件来放映射关系
原始形式
export function formatFood(type) {
if (type == 'PG' || type == 'TZ' || type == 'XJ' || type == 'XG' || type == 'LZ' || type == 'TG') {
return '水果';
} else if (type == 'NR' || type == 'ZR' || type == 'JR' || type == 'YR' || type == 'YR' || type == 'GR') {
return '肉类';
} else if (type == 'NG' || type == 'DG' || type == 'SG' || type == 'QZ' || type == 'LJ' || type == 'HLB') {
return '蔬菜';
} else if (type == 'DL') {
return '豆类';
} else if (type == 'GL') {
return '谷类';
} else if (type == 'ML') {
return '面类';
}
......
}
修改后:
1.建一个food-map.js文件存放映射关系;
/**
* 食物映射表
*/
export default {
'PG,TZ,XJ,XG,LZ,TG':'水果',
'NR,ZR,JR,YR,ER,GR':'肉类',
'NG,DG,SG,QZ,LJ,HLB':'蔬菜',
DL:'豆类',
GL:'谷类',
ML:'面类',
......
}
2.在公共方法里面进行逻辑操作;
import foodEnum from '@/core/food-map.js';
export function formatZYJD(type) {
//foodEnum为引进来的映射文件
for (const key in foodEnum) {
const foodKey = key.split(',')
if (foodKey.includes(type)) {
return foodEnum[foodKey]
}
}
return '--'
}