字典状态管理:基于 Vue3 + Pinia 的工程化实践

优雅实现字典状态管理:基于 Vue3 + Pinia

摘要:一份优雅的 Vue3 + Pinia 字典状态管理实践,解决数据复用、类型提示与性能缓存的终极方案,让你的项目从此告别散落各处的字典逻辑。话不多说,上代码。

1. Pinia Store 实现

javascript 复制代码
import { defineStore } from 'pinia';

export const useDictStore = defineStore('dict', {
    state: () => ({
        dict: [],
    }),
    
    actions: {
        // 获取指定字典类型
        getDict(key) {
            try {
                const item = this.dict.find(item => item.key === key);
                return item ? item.value : null;
            } catch (e) {
                console.error('获取字典失败:', e);
                return null;
            }
        },

        // 设置字典数据
        setDict(key, value) {
            if (!key || typeof key !== 'string') return;
            // 避免重复添加
            const index = this.dict.findIndex(item => item.key === key);
            if (index !== -1) {
                this.dict[index].value = value;
            } else {
                this.dict.push({ key, value });
            }
        },

        // 移除字典数据
        removeDict(key) {
            try {
                const index = this.dict.findIndex(item => item.key === key);
                if (index !== -1) {
                    this.dict.splice(index, 1);
                    return true;
                }
                return false;
            } catch (e) {
                console.error('移除字典失败:', e);
                return false;
            }
        },
        
        // 清空所有字典数据
        clearAll() {
            this.dict = [];
        }
    },
});

2. Hook 封装

ini 复制代码
import { ref, toRefs } from 'vue';
import { useDictStore } from '@/stores/dict';
import { getHttpDicts } from '/@/api/dict'; // 根据key获取字典接口

export function useDict(...args) {
    const res = ref({});
    const dictStore = useDictStore();
    
    args.forEach((dictType) => {
        res.value[dictType] = [];
        const dicts = dictStore.getDict(dictType);
        
        if (dicts) {
            res.value[dictType] = dicts;
        } else {
            getHttpDicts(dictType).then((resp) => {
                const dictData = resp.data.map((p) => ({
                    label: p.label,
                    value: p.value,
                }));
                res.value[dictType] = dictData;
                dictStore.setDict(dictType, dictData);
            }).catch(error => {
                console.error(`获取字典${dictType}失败:`, error);
            });
        }
    });
    
    return toRefs(res.value);
}

2. 使用示例

javascript 复制代码
import { useDict } from '@/hooks/useDict';
const { user_status, order_type } = useDict('user_status', 'order_type');
相关推荐
zhifou1234563 小时前
Vue基础(二)
前端·javascript·vue.js
你脑门上的脚印5 小时前
Vue 项目从零实现语音转文字、文字转语音功能(完整可用 + 踩坑指南)
前端·vue.js
lemon_yyds7 小时前
H5 页面嵌入 APP 的 web-view 时-调用原生能力(uniapp)
vue.js
ITmaster07319 小时前
Vibe Coding 时代:Vue 消失了还是 React 太强?
前端·vue.js·react.js
万敏9 小时前
Vue3 全栈实战第七周:错误处理与请求层封装实战记录
vue.js·node.js·全栈
请你吃div10 小时前
Electron 从零开始的新手开发教程
vue.js·windows·electron
咏方舟【长江支流】12 小时前
【前端1】单据编辑 -EasyUI/Vue/React/Bootstrap 主流框架实现订单单据主子表显示和编辑比较,哪个你最易入门?
前端·vue.js·easyui·咏方舟-长江支流·userbaodatagrid
m0_5791466512 小时前
Element UI 表格合并单元格完全指南:从原理到实战
前端·vue.js·elementui
雪芽蓝域zzs13 小时前
Prettier (代码格式化)配置详解
前端·vue.js
运维全栈笔记16 小时前
Vue + Spring Boot 前后端分离项目部署笔记(若依 RuoYi-Vue 3.9.2)
运维·服务器·vue.js·spring boot·笔记·开源·开源软件