/** * 字典工具 —— 通用字典加载、缓存、翻译 * 使用方式: * import { loadDict, getDictText, getDictColumns } from '@/util/dictUtil'; * loadDict('caseType'); // 加载字典(自动缓存) * getDictText('caseType', 0); // 翻译 value → text * getDictColumns('caseType'); // 获取 [{text, value}] 用于 van-picker */ import { queryDict } from '@/api/enterprise'; // 内存缓存 { dictType → [{text, value}] } const dictStore = {}; // sessionStorage key 生成 const cacheKey = (dictType) => `DICT_CACHE::${dictType}`; /** * 解析接口响应,兼容多种结构 */ const parseRows = (res) => { if (Array.isArray(res)) return res; if (res && Array.isArray(res.rows)) return res.rows; if (res && Array.isArray(res.data)) return res.data; if (res && res.data && Array.isArray(res.data.rows)) return res.data.rows; return []; }; /** * 标准化为 [{text, value}] */ const normalizeColumns = (rows) => { return rows.map(item => ({ text: item.dictLabel || item.label || item.name || '', value: item.dictValue || item.value || item.code || '' })).filter(c => c.text); }; /** * 加载指定字典类型(含 sessionStorage 缓存) * @param {string} dictType 字典类型 * @param {Function} [onSuccess] 可选回调,接收 columns [{text, value}] * @param {Function} [onError] 可选失败回调 */ export const loadDict = (dictType, onSuccess, onError) => { // 内存命中直接返回 if (dictStore[dictType] && dictStore[dictType].length > 0) { onSuccess && onSuccess(dictStore[dictType]); return; } // sessionStorage 命中 const cached = sessionStorage.getItem(cacheKey(dictType)); if (cached) { try { const columns = JSON.parse(cached); if (Array.isArray(columns) && columns.length > 0) { dictStore[dictType] = columns; onSuccess && onSuccess(columns); return; } } catch (e) { /* 解析失败继续走接口 */ } } // 请求接口 queryDict({ dictType }, (res) => { const columns = normalizeColumns(parseRows(res)); dictStore[dictType] = columns; if (columns.length > 0) { sessionStorage.setItem(cacheKey(dictType), JSON.stringify(columns)); } onSuccess && onSuccess(columns); }, (err) => { onError && onError(err); }); }; /** * 获取字典翻译文本 * @param {string} dictType 字典类型 * @param {*} val 字典值 * @param {string} [fallback='-'] 未匹配时的降级显示 * @returns {string} */ export const getDictText = (dictType, val, fallback) => { if (val === undefined || val === null || val === '') return fallback !== undefined ? fallback : '-'; const columns = dictStore[dictType] || []; const key = String(val); const found = columns.find(c => String(c.value) === key); return found ? found.text : (fallback !== undefined ? fallback : val); }; /** * 获取字典列表(用于 van-picker :columns) * @param {string} dictType * @returns {Array} [{text, value}] */ export const getDictColumns = (dictType) => { return dictStore[dictType] || []; };