/* * ✨ 字典工具类函数 ✨ * */ import utils from '@/utils.js' /** * 通过字典编码获取字典 * @param {String} code 字典编码 * @return {Array} 字典 * @example * getDictionaryByCode('xxx') // 获取'xxx'字典编码对应的字典数组 * */ export function getDictionaryByCode(code) { if (!code) return [] return utils.getDictItemsFromCache(code) || [] } /** * 字典转义(转义、翻译) * @param {Array} dictionary 字典数组 * @param {String} [val] 需转义内容 * @param {Object} [option] 转义配置项 * @param {String} [option.valueKey] 需转义字段键名 * @param {String} [option.labelKey] 对应字段键名 * @param {Boolean} [option.dictionaryType] true 为转义 false 为翻译 * @param {Boolean} [option.congruent] 为转义是匹配值为全等于还是等于 * @returns {String} 转义后的内容 * @example * */ export function dictionaryEscape(dictionary = [], val = '', option = {}) { if (!(Array.isArray(dictionary) && dictionary.length)) return '' option = { valueKey: 'value', labelKey: 'name', dictionaryType: true, congruent: true, ...option } const {valueKey, labelKey, dictionaryType, congruent} = option const item = dictionary.find(i => { const dictionaryValue = i[dictionaryType ? valueKey : labelKey] // 字典值 let condition = dictionaryValue === val // 返回条件 if (!congruent) condition = dictionaryValue == val return condition }) || {} return item[dictionaryType ? labelKey : valueKey] || '' } /** * 可通过指定字典编码转义 * @param {String} code 字典编码 * @param {String} [val] 需转义内容 * @param {Object} [option] 转义配置项 * @param {String} [option.valueKey] 需转义字段键名 * @param {String} [option.labelKey] 对应字段键名 * @param {Boolean} [option.dictionaryType] true 为转义 false 为翻译 * @param {Boolean} [option.congruent] 为转义是匹配值为全等于还是等于 * @returns {String} 转义后的内容 * */ export function dictionaryEscapeAdoptCoding(code, val = '', option = {}) { return dictionaryEscape(getDictionaryByCode(code), val, option) }