通过返回的key值匹配字典中的value值

news/2025/2/27 7:41:20

需求

页面中上面搜索项有获取字典枚举接口,table表格中也有根据key匹配字典中的value

方案一

在这里插入图片描述

需要做到的要求

  • 这里上面下拉列表是一个组件获取的字典,下面也是通过字典匹配,所以尽量统一封装一个函数,每个组件保证最少变动
  • table表格中如果filters中更改,会获取多次接口,—使用闭包让只获取一次接口,节省性能
  • filter中又是必须同步函数,异步函数报错,所以不能使用async,await
  • 最好请求接口之后存储起来下次直接拿不用请求了

综上

utils/dictionary.js

javascript">import { getDicValue } from '@/api/systemManage'
import store from '@/store'
/**
 * 获取字典数据
 * @param {Boolean} hasAllOption 是否包含全部选项
 */
export function getDicValueList(dictClassCode, hasAllOption = true) {
  const dictionaryCache = store.state.dictionary.dictionaryCache || {}
  return new Promise((resolve, reject) => {
    let optionList = []
    if (dictionaryCache[dictClassCode]) {
      const dicList = JSON.parse(JSON.stringify(dictionaryCache[dictClassCode]))
      if (hasAllOption) {
        optionList = [ { value: '', label: '全部' }, ...dicList]
      } else {
        optionList = [...dicList]
      }
      resolve(optionList)
    } else {
      getDicValue(dictClassCode).then(response => {
        console.log('字典调用', dictClassCode)
        const dicList = response.value || []
        store.dispatch('dictionary/setDictionaryCache', { key: dictClassCode, value: dicList })
        if (hasAllOption) {
          optionList = [ { value: '', label: '全部' }, ...dicList]
        } else {
          optionList = [...dicList]
        }
        resolve(optionList)
      }).catch(error => {
        reject([])
      })
    }
  })
}

/**
 * 获取字典数据并返回一个闭包函数
 * @param {string} dictClassCode 字典类代码
 * @param {string} noTitle 默认值,当找不到匹配项时返回
 * @returns {Promise<Function>} 返回一个闭包函数,该函数可以根据 value 获取 label
 */
export async function getDicValueName(dictClassCode, noTitle = "--") {
  try {
    const response = await getDicValueList(dictClassCode, false)
    const listData = response || []
    return (value) => {
      let label = noTitle
      listData.some(item => {
        if (item.value === value) {
          label = item.label
          return true
        }
      })
      return label
    }
  } catch (err) {
    console.error(err)
    return (value) => noTitle
  }
}

下拉框组件

javascript">created () {
    this.getOptionLists()
  },

getOptionLists() {
      if (this.dictClassCode) {
        getDicValueList(this.dictClassCode).then(res => {
          this.optionLists = res
        })
      } else {
        this.optionLists = this.options
      }
    },

table组件中

javascript"><span>{{ filterStateName(scope.row.state) }}</span>


import { getDicValueName } from '@/utils/dictionary'

created() {
    this.initDictionary()
  },

methods: {
async initDictionary() {
      try {
        this.filterStateName = await getDicValueName('DC_DICTIONARY_STATE')
      } catch (error) {
        console.error('Failed to fetch dictionary:', error)
        this.filterStateName = (value) => '--'
      }
    },
   }

问题: 但是这种因为一进页面这两个组件都是去获取字典,所以还是从接口拿的数据,会调用两次接口

方案二(建议)

方案:接下来优化可以通过路由导航预加载,先获取字典之后,在加载页面
router.js

javascript">

// 预加载字典
export function preloadDictionary(dictClassCodeList) {
  const pList = []
  dictClassCodeList.forEach(dictClassCode => {
    const p = getDicValueList(dictClassCode)
    pList.push(p)
  })
  return Promise.all(pList)
}


// 预加载字典
router.beforeEach((to, from, next) => {
  if(to.meta && to.meta.dictClassCodeList&& to.meta.dictClassCodeList.length > 0) {
    preloadDictionary(to.meta.dictClassCodeList).then(res => {
      next()
    })
  } else {
    next()
  }
})

总结:其实这里都可以规定直接预加载字典,到页面直接使用加载后的字典,注册个全局filters就行,根本不用上面那些,先都记录上,后期根据需求灵活应用吧


http://www.niftyadmin.cn/n/5869740.html

相关文章

Spring Data JPA vs MyBatis:ORM框架如何选择?

在选择ORM框架时&#xff0c;Spring Data JPA和MyBatis是两个常见的选择&#xff0c;它们各有优缺点&#xff0c;适用于不同的场景。以下是两者的对比&#xff0c;帮助你做出选择&#xff1a; 1. Spring Data JPA 优点&#xff1a; 开发效率高&#xff1a;通过简单的接口定义和…

【TCAD】Sentaurus 中的“陷阱trap”仿真设置

13.1 陷阱类型 13.2 定义陷阱 13.3 陷阱态密度的类型 13.4 陷阱空间分布 13.5 陷阱占据 13.6 陷阱横截面 13.7 陷阱作为掺杂 13.8 陷阱填充控制 13.9 陷阱可视化 目标 演示如何使用 Sentaurus 设备在模拟中使用陷阱。13.1 陷阱类型

adb的安装

1、概念 &#xff08;1&#xff09;adb&#xff08;android debug bridge&#xff09;安卓调试桥&#xff0c;用于完成电脑和手机之间的通信控制。 &#xff08;2&#xff09;xcode来完成对于ios设备的操控&#xff0c;前提是有个mac电脑。 2、adb的安装 &#xff08;1&…

Unity XR-XR Interaction Toolkit开发使用方法(十)组件介绍(XR Interaction Group)

目录 一、插件介绍 二、主要组件 XR Interaction Manager XR Controller XR Interactor XR Direct Interactor XR Ray Interactor XR Socket Interactor XR Gaze Interactor 三、XR Interaction Group 1、组件介绍 2、核心功能与特点 优先级与冲突管理 动态交互切…

Android内存优化指南:从数据结构到5R法则的全面策略

目录 一、APP 内存限制 二、内存的三大问题 2.1、内存抖动(Memory Churn) 2.1.1 频繁创建短生命周期对象 2.1.2 系统API或第三方库的不合理使用 2.1.3 Handler使用不当 2.2、内存泄漏(Memory Leak) 2.2.1 静态变量持有Activity或Context引用 2.2.2 未取消的回调或…

【AGI】DeepSeek开源周:The whale is making waves!

DeepSeek开源周&#xff1a;The whale is making waves&#xff01; 思维火花引言一、DeepSeek模型体系的技术演进1. 通用语言模型&#xff1a;DeepSeek-V3系列2. 推理优化模型&#xff1a;DeepSeek-R1系列3. 多模态模型&#xff1a;Janus系列 二、开源周三大工具库的技术解析1…

2025年证券从业资格考试报名全流程图解✅

⏬3月证券考试信息汇总 ✅报名时间&#xff1a;3月4日15时至3月7日15时 ✅退费时间&#xff1a;3月6日15时至3月9日15时 ✅准考证打印&#xff1a;3月19日15时至3月22日18时 报名直达&#xff1a;中国证券业协会网站 ⏬注册报名流程 第1步&#xff1a;登录【中国证券业协…

【Java分布式】基本概念

分布式 基本概念 1、微服务 微服务是由单一应用程序构成的小服务&#xff0c;拥有自己的进程与轻量化处理&#xff0c;服务依业务功能设计&#xff0c;以全自动的方式部署&#xff0c;与其他服务使用HTTP API通讯。同时&#xff0c;服务会使用最小规模的集中管理 &#xff0…