feat: 增加enum.js

This commit is contained in:
caoqianming 2024-03-13 09:51:37 +08:00
parent 9479de2460
commit 6fa74980ca
1 changed files with 59 additions and 0 deletions

59
src/utils/enum.js Normal file
View File

@ -0,0 +1,59 @@
/**
* 枚举创建工厂构造函数扩展枚举对象keysvalues(含key值的[{key,text,type}])formatter
* @param {*} enumObj 枚举值支持标准模式{key:{text,type},}简单模式{key:text,}会自动转换为标准模式
* @param {*} keyParseFunc key的转换函数默认null如果key为整数则传 parseInt
*/
export default function EnumFactory(enumObj, keyParseFunc = null) {
//复制继承enumObj
Object.assign(this, enumObj)
// keys枚举的key集合[key]
Object.defineProperty(this, 'keys', {
value: keyParseFunc ? Object.keys(enumObj).map(s => keyParseFunc(s)) : Object.keys(enumObj)
})
// 处理 values
let values = []
const ovalues = Object.values(enumObj)
// 主要区分下value是简单类型字符串还是对象类型
if (typeof ovalues[0] === 'string') {
ovalues.forEach((text, index) => {
const obj = { key: this.keys[index], text }
values.push(obj)
this[this.keys[index]] = obj
})
}
else {
ovalues.forEach((item, index) => {
item.key = this.keys[index]
values.push(item)
})
}
// 设置values属性
Object.defineProperty(this, 'values', { value: values })
// formatterelement中表格绑定枚举数据文本的formatter函数
// r、c为行列可传入null
Object.defineProperty(this, 'formatter', {
value: function(r, c, value) {
return values.filter(v => v.key == value || v.text == value)[0]?.text || 'notfound'
}
})
//枚举定义的数据都是常量,不可修改,冻结一下
Object.freeze(this)
}
export const runningStateEnum = new EnumFactory({
10: { text: '运行', type: 'success' },
20: { text: '待机', type: 'primary' },
30: { text: '停机', type: 'warning' },
40: { text: '故障', type: 'danger' },
50: { text: '未知', type: 'info' },
}, parseInt)
export const drainTypeEnum = new EnumFactory({
'product': '生产工艺',
'mtrans': '物料输送',
'mstore':'物料储存'
})