字典状态管理:基于 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');
相关推荐
前端开发爱好者10 小时前
尤雨溪官宣:"新玩具" 比 Prettier 快 45 倍!
前端·javascript·vue.js
欧阳呀10 小时前
Vue+element ui导入组件封装——超级优雅版
前端·javascript·vue.js·elementui
华仔啊12 小时前
用 Vue3 + Canvas 做了个超实用的水印工具,同事都在抢着用
前端·vue.js·canvas
炒毛豆13 小时前
uniapp微信小程序+vue3基础内容介绍~(含标签、组件生命周期、页面生命周期、条件编译(一码多用)、分包))
vue.js·微信小程序·uni-app
岁月宁静14 小时前
在 Vue 3.5 中优雅地集成 wangEditor,并定制“AI 工具”下拉菜单(总结/润色/翻译)
前端·javascript·vue.js
Dolphin_海豚15 小时前
@vue/reactivity
前端·vue.js·面试
菜狗的小小笔记_15 小时前
Vue3 实用技巧
vue.js
勇敢di牛牛19 小时前
vue3 + mars3D 三分钟画一个地球
前端·vue.js
我是日安21 小时前
从零到一打造 Vue3 响应式系统 Day 27 - toRef、toRefs、ProxyRef、unref
前端·javascript·vue.js
Q_Q196328847521 小时前
python+vue的在线租房 房屋租赁系统
开发语言·vue.js·spring boot·python·django·flask·node.js