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/utils/dict.js

126 lines
3.0 KiB

/**
* 字典工具类
* 用于在组件中方便地使用字典数据
*/
import store from '../store';
class Dict {
constructor() {
this.dictData = {};
}
/**
* 初始化字典
* @param {Array} dicts 字典配置数组,格式:['dictType'] 或 [{type: 'dictType'}]
* @returns {Promise}
*/
async init(dicts) {
if (!dicts || !Array.isArray(dicts)) {
return Promise.resolve();
}
try {
// 提取字典类型,支持字符串数组或对象数组格式
const types = dicts.map(item => {
return typeof item === 'string' ? item : item.type;
});
// 批量获取字典数据
await store.dispatch('dict/getDicts', types);
// 处理字典数据
dicts.forEach(item => {
const type = typeof item === 'string' ? item : item.type;
this.dictData[type] = store.getters.dictByType(type);
});
return Promise.resolve();
} catch (error) {
console.error('初始化字典失败:', error);
return Promise.reject(error);
}
}
/**
* 获取字典数据
* @param {string} type 字典类型
* @returns {Array} 字典数据数组
*/
get(type) {
return this.dictData[type] || store.getters.dictByType(type) || [];
}
/**
* 根据字典值获取字典标签
* @param {string} type 字典类型
* @param {string|number} value 字典值
* @returns {string} 字典标签
*/
getLabel(type, value) {
const dict = this.get(type);
const item = dict.find(item => item.dictValue === value.toString());
return item ? item.dictLabel : '';
}
/**
* 根据字典标签获取字典值
* @param {string} type 字典类型
* @param {string} label 字典标签
* @returns {string} 字典值
*/
getValue(type, label) {
const dict = this.get(type);
const item = dict.find(item => item.dictLabel === label);
return item ? item.dictValue : '';
}
/**
* 刷新字典数据
* @param {string|Array} types 字典类型或类型数组
* @returns {Promise}
*/
async refresh(types) {
const typeArray = Array.isArray(types) ? types : [types];
await store.dispatch('dict/getDicts', typeArray);
// 更新本地字典数据
typeArray.forEach(type => {
this.dictData[type] = store.getters.dictByType(type);
});
}
}
/**
* 全局字典工具实例
*/
const dictUtil = new Dict();
/**
* Vue插件
*/
export default {
install(Vue) {
// 添加全局方法
Vue.prototype.$dict = dictUtil;
// 添加全局混入
Vue.mixin({
data() {
return {
dict: new Dict()
};
},
created() {
if (this.$options.dicts) {
this.dict.init(this.$options.dicts).then(() => {
this.$emit('dictReady', this.dict);
if (this.onDictReady && typeof this.onDictReady === 'function') {
this.onDictReady(this.dict);
}
});
}
}
});
}
};
export { dictUtil };