vue3中字典表相关业务自动化实现之useDict的用法

2,040 阅读1分钟

最近看了若依的前端代码,关于字典表的处理确实很实用,像我们平时在前端页面中使用到的一些固定的字典数据,如果不进行处理的话就是哪个页面用到都需要请求一遍,这样不仅浪费资源,写起来更是一些重复的请求代码。而若依里面的处理则是巧妙的简化了这类请求:

  • 在项目的系统管理中有页面可以进行可视化的配置字典表(这里后端也很巧妙,所有字典表都是一个接口通过type进行区分)
  • 前端在全局绑定一个useDict方法,来进行字典的请求(如果store中有数据就从store中取,如果store中没有就请求了放在store中,这样就不会有重复的请求了hhh)
  • 页面中在需要用到字典表的地方只需要调用useDict()方法就ok了,所有字典表的返回数据也是一致的
1.在utils文件夹下创建dict.js
export function useDict(...args) {
  const res = ref({});
  return (() => {
    args.forEach((dictType, index) => {
      res.value[dictType] = [];
      const dicts = useDictStore().getDict(dictType);
      if (dicts) {
        res.value[dictType] = dicts;
      } else {
        getDictInfo(dictType).then(resp => {
          res.value[dictType] = resp.data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass }))
          useDictStore().setDict(dictType, res.value[dictType]);
        })
      }
    })
    return toRefs(res.value);
  })()
}

// analyze
// 遍历页面传过来的type值,如果store中有存储的值就从store中取,如果没有则进行请求

2.在main.js中给全局绑定useDict
app.config.globalProperties.useDict = useDict
3. 页面中使用 proxy.useDict() 来获取字典表数据
const { sys_user_sex } = proxy.useDict('sys_user_sex');