feat: app添加字典支持

property-only-app
wx-jincw 2 months ago
parent bba4bf4985
commit 363eb383d7

@ -227,3 +227,19 @@ export function getLiveList(page,limit) {
export function getQrcode(data) { export function getQrcode(data) {
return request.post('qrcode/get',data,{ noAuth: true }); return request.post('qrcode/get',data,{ noAuth: true });
} }
/**
* 批量获取字典数据
* @param array types 字典类型数组
*/
export function sysdicttypeTypesApi(types) {
return request.post('system/dict/types', { types }, { useAdminUrl: true });
}
/**
* 获取单个字典数据
* @param string type 字典类型
*/
export function getDict(type) {
return request.get(`system/dict/${type}`, {}, { useAdminUrl: true });
}

@ -5,6 +5,7 @@ import Cache from './utils/cache'
import util from 'utils/util' import util from 'utils/util'
import configs from './config/app.js' import configs from './config/app.js'
import * as Order from './libs/order'; import * as Order from './libs/order';
import Dict from './utils/dict.js';
Vue.prototype.$util = util; Vue.prototype.$util = util;
Vue.prototype.$config = configs; Vue.prototype.$config = configs;
@ -13,6 +14,9 @@ Vue.prototype.$eventHub = new Vue();
Vue.config.productionTip = false Vue.config.productionTip = false
Vue.prototype.$Order = Order; Vue.prototype.$Order = Order;
// 注册字典插件
Vue.use(Dict);
// #ifdef H5 // #ifdef H5
import { parseQuery } from "./utils"; import { parseQuery } from "./utils";
import Auth from './libs/wechat'; import Auth from './libs/wechat';

@ -8,5 +8,10 @@ export default {
home: state => state.app.home, home: state => state.app.home,
chatUrl: state => state.app.chatUrl, chatUrl: state => state.app.chatUrl,
systemPlatform: state => state.app.systemPlatform, systemPlatform: state => state.app.systemPlatform,
productType: state => state.app.productType productType: state => state.app.productType,
// 字典相关getter
dict: state => state.dict.dict,
dictData: state => state.dict.dictData,
// 根据字典类型获取字典数据
dictByType: state => type => state.dict.dictData[type] || []
}; };

@ -0,0 +1,106 @@
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;
}
},
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 || []).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
};

@ -1,5 +1,7 @@
import app from "./app"; import app from "./app";
import dict from "./dict";
export default { export default {
app app,
dict
}; };

@ -0,0 +1,127 @@
/**
* 字典工具类
* 用于在组件中方便地使用字典数据
*/
import store from '../store';
import { getDict, sysdicttypeTypesApi } from '../api/api';
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 };

@ -1,5 +1,6 @@
import { import {
HTTP_REQUEST_URL, HTTP_REQUEST_URL,
HTTP_ADMIN_URL,
HEADER, HEADER,
TOKENNAME, TOKENNAME,
HEADERPARAMS HEADERPARAMS
@ -16,9 +17,10 @@ import store from '../store';
*/ */
function baseRequest(url, method, data, { function baseRequest(url, method, data, {
noAuth = false, noAuth = false,
noVerify = false noVerify = false,
useAdminUrl = false
}, params) { }, params) {
let Url = HTTP_REQUEST_URL,header = HEADER let Url = useAdminUrl ? HTTP_ADMIN_URL : HTTP_REQUEST_URL, header = HEADER
if (params != undefined) { if (params != undefined) {
header = HEADERPARAMS; header = HEADERPARAMS;
} }
@ -33,9 +35,9 @@ function baseRequest(url, method, data, {
} }
if (store.state.app.token) header[TOKENNAME] = store.state.app.token; if (store.state.app.token) header[TOKENNAME] = store.state.app.token;
return new Promise((reslove, reject) => { return new Promise((reslove, reject) => {
Url=HTTP_REQUEST_URL||'http://api.front.hdq.xbdzz.cn' const apiPrefix = useAdminUrl ? '/api/' : '/api/front/'
uni.request({ uni.request({
url: Url + '/api/front/' + url, url: Url + apiPrefix + url,
method: method || 'GET', method: method || 'GET',
header: header, header: header,
data: data || {}, data: data || {},

Loading…
Cancel
Save