You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
crmeb/app/store/modules/dict.js

107 lines
2.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const state = {
dict: [],
dictData: {}
};
const mutations = {
SET_DICT: (state, { key, value }) => {
if (key && key !== '') {
// 检查是否已存在该字典
const existingIndex = state.dict.findIndex(item => item.key === key);
if (existingIndex > -1) {
// 更新现有字典
state.dict[existingIndex].value = value;
} else {
// 添加新字典
state.dict.push({ key, value });
}
// 同时更新dictData对象方便快速查找
state.dictData[key] = value;
state.dictData = { ...state.dictData };
}
},
REMOVE_DICT: (state, key) => {
try {
const index = state.dict.findIndex(item => item.key === key);
if (index > -1) {
state.dict.splice(index, 1);
delete state.dictData[key];
}
} catch (e) {
console.error('删除字典失败:', e);
}
},
CLEAN_DICT: (state) => {
state.dict = [];
state.dictData = {};
}
};
const actions = {
// 设置字典
setDict({ commit }, data) {
commit('SET_DICT', data);
},
// 删除字典
removeDict({ commit }, key) {
commit('REMOVE_DICT', key);
},
// 清空字典
cleanDict({ commit }) {
commit('CLEAN_DICT');
},
// 批量获取字典
async getDicts({ commit, state }, types) {
try {
// 先从状态中获取已有的字典
const existingDicts = {};
const needFetchTypes = [];
types.forEach(type => {
// 检查内存中是否有
if (state.dictData[type]) {
existingDicts[type] = state.dictData[type];
} else {
needFetchTypes.push(type);
}
});
// 如果所有字典都已存在,直接返回
if (needFetchTypes.length === 0) {
return existingDicts;
}
// 调用API获取需要的字典
const { sysdicttypeTypesApi } = require('../../api/api');
const res = await sysdicttypeTypesApi(needFetchTypes);
// 处理返回的数据
const fetchedDicts = {};
(res.data || []).forEach(item => {
if (fetchedDicts[item.dictType]) {
fetchedDicts[item.dictType].push(item);
} else {
fetchedDicts[item.dictType] = [item];
}
});
// 更新状态
Object.keys(fetchedDicts).forEach(key => {
commit('SET_DICT', { key, value: fetchedDicts[key] });
});
// 合并已有的和新获取的字典
return { ...existingDicts, ...fetchedDicts };
} catch (error) {
console.error('获取字典失败:', error);
return {};
}
}
};
export default {
namespaced: true,
state,
mutations,
actions
};