前端代码中应该避免直接使用接口返回的枚举值:0、1、2、3...
使用语义化的方式来处理枚举值
定义一个枚举对象创建函数
// 创建枚举对象,用于界面显示转换
function createEnumObject(enums) {
let labels = null
let values = null
return {
getLabels() {
if (!labels) {
labels = enums.map((item) => item.label)
}
return labels
},
getValues() {
if (!values) {
values = enums.map((item) => item.value)
}
return values
},
getLabel(value) {
let index = this.getValues().indexOf(value)
if (index > -1) {
return this.getLabels()[index]
}
},
getValue(label) {
let index = this.getLabels().indexOf(label)
if (index > -1) {
return this.getValues()[index]
}
},
getItem(valueOrLabel) {
let index = this.getValues().indexOf(valueOrLabel)
if (index < 0) {
index = this.getLabels().indexOf(valueOrLabel)
}
if (index > -1) {
return enums[index]
}
},
}
}
创建枚举对象
// 枚举值,用于逻辑判断
const statusEnum = {
// 待支付
WaitPay: 0,
// 已完成
Success: 1,
// 已取消
Cancel: 2,
}
// 枚举值配置,用于属性扩展
const statusEnumConfig = [
{
value: statusEnum.WaitPay,
label: '待支付',
color: 'yellow',
// 支付 取消支付
actions: ['pay', 'cancel'],
},
{
value: statusEnum.Success,
label: '已完成',
color: 'green',
// 查看详情 退款
actions: ['detail', 'return'],
},
{
value: statusEnum.Cancel,
label: '已取消',
color: 'red',
// 查看详情
actions: ['detail'],
},
]
// 枚举值对象,用于数值转换
const statusEnumObj = createEnumObject(statusEnumConfig)
使用示例
console.log(statusEnumObj.getItem(1))
// {
// value: 1,
// label: '已完成',
// color: 'green',
// actions: [ 'detail', 'return' ]
// }
console.log(statusEnumObj.getValue('已完成'))
// 1
// 没有对应的值返回undefined
console.log(statusEnumObj.getValue(1))
// undefined
// 接口返回的真实数值,转换为显示值
console.log(statusEnumObj.getLabel(1))
// 已完成
// 接口返回的数值,做逻辑判断
console.log(statusEnum.Success == 1);
// true