import Vue from 'vue' import Vuex from 'vuex' import * as api from '@/api' Vue.use(Vuex) const store = new Vuex.Store({ state: { // 存放状态 configList: [], departmentList: [], categoryList: [] }, mutations: { // 构造用于uv-picker的树状结构数组 setCategoryList(state, data) { // 将返回的平面数组data 根据pid和hasChild组装成两个数组,其一为pid为0的父级一维数组,其二为pid不为0的子级二维数组,其中pid相同的排一起 不同的分为不同子数组,并且按顺序排序,比如第一个为[中国,美国] 第二个按顺序为[[上海,福建],[纽约,华盛顿]] // 分离父级和子级数据 const parentCategories = data.filter(item => item.pid === 0 || item.pid === '0') const childCategories = data.filter(item => item.pid !== 0 && item.pid !== '0') // 构建父级一维数组 const parentArray = parentCategories.map((item) => { return { label: item.name || item.title || item.categoryName, value: item.id } }) // 构建子级二维数组 const childArray = [] parentCategories.forEach(parent => { const children = childCategories .filter(child => child.pid === parent.id) .map(child => { return { label: child.name || child.title || child.categoryName, value: child.id } }) childArray.push(children.length > 0 ? children : [{ label: '全部', value: 0 }]) }) // 组装最终结果 state.categoryList = [parentArray, childArray] }, setConfigList(state, data) { state.configList = data }, setDepartmentList(state, data) { state.departmentList = data }, // }, actions: { // 查询配置列表 async getConfig({ commit }) { const res = await api.config.queryConfigList() // 要求变成键值对的样子 const config = res.result.records.reduce((acc, item) => { if (!item.paramCode) { console.log('paramCode为空', item); return acc } acc[item.paramCode] = item return acc }, {}) commit('setConfigList', config) }, // 查询部门列表 async getDepartment({ commit }) { const res = await api.config.queryDepartmentList() commit('setDepartmentList', res.result.records) }, // 获取分类列表 async getCategory({ commit }) { const res = await api.config.queryCategoryList() commit('setCategoryList', res.result.records) }, // 初始化数据 async initData({ dispatch, state }) { // 检查是否已初始化 if (state.configList.length > 0 && state.departmentList.length > 0 && state.categoryList.length > 0) { console.log('配置数据已初始化,无需重复初始化') return } try { await Promise.all([ dispatch('getConfig'), dispatch('getDepartment'), dispatch('getCategory'), ]) console.log('所有配置数据初始化完成') } catch (error) { console.error('配置数据初始化失败:', error) } }, } }) export default store