小程序缓存数据字典
import { getDict } from '@/api/profile';
const CACHE_KEY = 'DICT_CACHE';
let dictCache = new Map();
// 初始化时加载缓存
const loadCache = () => {
const cache = uni.getStorageSync(CACHE_KEY);
if (cache) {
dictCache = new Map(JSON.parse(cache));
}
};
// 保存缓存到Storage
const saveCache = () => {
uni.setStorageSync(CACHE_KEY, JSON.stringify([...dictCache]));
};
/**
* 获取字典数据(支持多字段、缓存)
* @param {string} dictCodes - 字典编码,支持逗号拼接,如 'VISIT_REASON,VISITOR_TYPE'
* @param {string} url - 请求 URL
* @returns {Promise<Object>} 返回包含所有字典的 map 对象,如 { VISIT_REASON: { ... }, VISITOR_TYPE: { ... } }
*/
// 获取字典数据(带缓存和持久化)
export const dictWithUrl = async(dictCodes) => {
loadCache(); // 每次调用先加载缓存
const codes = typeof dictCodes === 'string' ? dictCodes.split(',').map(code => code.trim()) : dictCodes;
// 检查缓存
const cachedData = {};
const uncachedCodes = codes.filter(code => {
if (dictCache.has(code)) {
cachedData[code] = dictCache.get(code);
return false;
}
return true;
});
// 全部命中缓存
if (!uncachedCodes.length) {
return { data: cachedData };
}
// 请求未缓存数据
const res = await getDict(uncachedCodes.join(','));
// 成功后合并更新缓存
Object.entries(res.data).forEach(([code, data]) => {
dictCache.set(code, data);
cachedData[code] = data;
});
saveCache(); // 保存最新缓存
return { data: cachedData };
};
// 清空缓存(可选)
export const clearDictCache = () => {
dictCache.clear();
uni.removeStorageSync(CACHE_KEY);
};
export const getDictLabel = (dictOptions, dictKey, value, defaultValue = '') => {
if (!dictKey) return value || defaultValue;
if (dictOptions[dictKey]) {
return dictOptions[dictKey][value] || value || defaultValue;
}
};