From 6fa74980ca91f0dd425c076ff1bf5fd469df632e Mon Sep 17 00:00:00 2001 From: caoqianming Date: Wed, 13 Mar 2024 09:51:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0enum.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/utils/enum.js | 59 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/utils/enum.js diff --git a/src/utils/enum.js b/src/utils/enum.js new file mode 100644 index 00000000..e5910710 --- /dev/null +++ b/src/utils/enum.js @@ -0,0 +1,59 @@ +/** + * 枚举创建工厂(构造函数),扩展枚举对象:keys、values(含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 }) + + // formatter:element中表格绑定枚举数据文本的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':'物料储存' +}) \ No newline at end of file