| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- import { defineStore } from 'pinia';
- import { ref } from 'vue';
- import { getAllDataDictList as getList } from '@/api';
- export const useDataDictStore = defineStore('dataDict', () => {
- const dataDict = ref([]);
- const map = new Map();
- let isLoaded = false;
- let loadingPromise = null;
- /**
- * 加载数据字典
- */
- const loadDataDictList = async () => {
- if (isLoaded) {
- return dataDict.value;
- }
- // 应用启动和页面初始化可能同时触发,复用同一个请求,避免重复加载。
- if (loadingPromise) {
- return loadingPromise;
- }
- loadingPromise = getList()
- .then(response => {
- if (Array.isArray(response?.data)) {
- dataDict.value = response.data;
- map.clear();
- isLoaded = true;
- }
- return dataDict.value;
- })
- .catch(() => dataDict.value)
- .finally(() => {
- loadingPromise = null;
- });
- return loadingPromise;
- };
- /**
- * 获取type对应字典列表
- * @param type
- */
- const getDataDictList = type => {
- if (map.has(type) && map.get(type).length > 0) {
- return map.get(type);
- }
- const list = dataDict.value.filter(item => item.dictType === type);
- // const locale = uni.getLocale()
- // // label格式为'xxxx~~en**aaaa~~ru**bbbb', 根据当前语言环境进行处理
- // const list = dataDict.value.filter(item => item.dictType === type)
- // .map(item => {
- // if (item.label.includes('~~') && item.label.includes('**')) {
- // const s = item.label.split('~~')
- // if (locale.startsWith('zh')) {
- // item.label = s[0]
- // } else if (locale.startsWith('ru')) {
- // const s2 = s[2].split('**')
- // item.label = s2[1]
- // } else {
- // const s1 = s[1].split('**')
- // item.label = s1[1]
- // }
- // }
- // return JSON.parse(JSON.stringify(item))
- // })
- map.set(type, list);
- return list;
- };
- const getStrDictOptions = dictType => {
- // 获得通用的 DictDataType 列表
- const dictOptions = getDataDictList(dictType);
- // 转换成 string 类型的 StringDictDataType 类型
- // why 需要特殊转换:避免 IDEA 在 v-for="dict in getStrDictOptions(...)" 时,el-option 的 key 会告警
- const dictOption = [];
- dictOptions.forEach(dict => {
- dictOption.push({
- ...dict,
- value: dict.value + '',
- });
- });
- return dictOption;
- };
- const getIntDictOptions = dictType => {
- // 获得通用的 DictDataType 列表
- const dictOptions = getDataDictList(dictType);
- // 转换成 number 类型的 NumberDictDataType 类型
- // why 需要特殊转换:避免 IDEA 在 v-for="dict in getIntDictOptions(...)" 时,el-option 的 key 会告警
- const dictOption = [];
- dictOptions.forEach(dict => {
- dictOption.push({
- ...dict,
- value: parseInt(dict.value + ''),
- });
- });
- return dictOption;
- };
- return {
- dataDict,
- getDataDictList,
- loadDataDictList,
- getStrDictOptions,
- getIntDictOptions,
- };
- });
|