前言
前端的同学们应该都涉及到过后端列表返回字典key,需要前端查询字典列表然后去匹配相关的文本的问题。
有时候是在页面初始化时就把所有的字典列表全部查询出来,感觉很不合理,可能当时我只使用到了一两个字典列表。
下面简单的实现了一个字典列表按需加载的功能,并非尽善尽美,有问题欢迎指出
实现原理
通过传入字典名的列表、字典名查询对应的字典列表集合
1、判断传入的字典名的列表、字典名在session中存储字典集合中哪些已经存在
2、将已在session中存在的字典从需要查询的字典名列表中剔除
3、根据处理过的字典名列表查询对应字典
4、合并已存储原始字典列表和新查询的字典列表并存入session
5、返回处理过的字典名的列表中的所有字典集合
实现代码
// 字典查询接口
import {queryDictByCodes} from '@/api'
export default {
namespaced: true,
actions: {
getDictByKey({
commit
}, dictKey) {
let dictResult = {} // 字典结果集
let _dictKey = [] // 需要查询的字典
const existingDicts = JSON.parse(sessionStorage.getItem('wealth_dicts')) // 已存入sessionStorage的字典
const existingDicts_Keys = existingDicts ? Object.keys(existingDicts) : [] // 已存入sessionStorage的字典的key集合
if (!Array.isArray(dictKey)) { // 单个字典值查询
if (existingDicts_Keys[dictKey] && existingDicts_Keys[dictKey].length) {
return Promise.resolve(existingDicts_Keys[dictKey])
} else {
_dictKey = [dictKey]
}
} else { // 多个字典值查询
const difKeys = dictKey.filter(v => !existingDicts_Keys.includes(v)) // 不存在sessionStorage的字典key
const existingKeys = dictKey.filter(v => existingDicts_Keys.includes(v)) // 存在sessionStorage的字典key
if (!difKeys.length) { // 要查询的字典都存在sessionStorage中
dictResult = dictKey.reduce((Obj, key) => {
Obj[key] = existingDicts[key]
return Obj
}, {})
return Promise.resolve(dictResult)
} else {
dictResult = existingKeys.reduce((Obj, key) => {
Obj[key] = existingDicts[key]
return Obj
}, {})
_dictKey = difKeys
}
}
if (_dictKey.length) {
return new Promise(async (resolve, reject) => {
await queryDictByCodes({
dictKeys: _dictKey
}).then(res => {
if (res.errorCode !== '000000') {
reject(res.errorMsg)
return
}
dictResult = {
...dictResult,
...res.data
}
// 将字典合集存入sessionStorage
sessionStorage.setItem('wealth_dicts', JSON.stringify({
...existingDicts,
...res.data
}))
resolve(dictResult)
})
})
}
}
}
}
使用
在合适时机调用即可
async init() {
// 字典key列表
const dictKeys = ['wp_custTier', 'wp_sex', 'wp_custSts']
// 查询所需字典
this.DICTS = await this.$store.dispatch('dict/getDictByKey', dictKeys)
}