字典数据
本小节,讲解前端如何使用 [系统管理 -> 字典管理] 菜单的字典数据,例如说字典数据的下拉框、单选 / 多选按钮、高亮展示等等。

# 1. 全局缓存
用户登录后,前端会从后端获取到全量的字典数据,缓存在 store 中。如下图所示:

这样,前端在使用到字典数据时,无需重复请求后端,提升用户体验。
字典数据同时缓存在浏览器的 sessionStorage 中,有效期 60 秒(见 src/store/modules/dict.ts (opens new window)):
- 刷新浏览器后,如果缓存还没过期,会继续使用缓存中的字典数据,不一定立即拿到后端最新的数据;过期后才会重新请求
- 如果需要立即使用最新的字典数据,调用
useDictStore().resetDict()(useDictStore从@/store/modules/dict引入):它会删除缓存,再重新请求后端。注意,store 的$reset()只重置 store 状态,不会删除缓存,两者不等价
# 2. DICT_TYPE
在 dict.ts (opens new window) 文件中,使用 DICT_TYPE 枚举了字典的 KEY。如下图所示:

后续如果有新的字典 KEY,需要你自己进行添加。
# 3. DictTag 字典标签
<dict-tag /> (opens new window) 组件,翻译字段对应的字典展示文本,并根据 colorType、cssClass 进行高亮。使用示例如下(模板片段,row 为表格列 #default="{ row }" 插槽中的行数据):
<!--
type: 字典 KEY
value: 字典值
-->
<dict-tag :type="DICT_TYPE.SYSTEM_LOGIN_TYPE" :value="row.logType" />

另外,如果使用 《CRUD 组件》 中可选的 Table 组件,可以直接给 columns 中的列设置 dictType 属性,该列会自动使用 <dict-tag /> 展示,例如 { field: 'status', label: '状态', dictType: DICT_TYPE.COMMON_STATUS }。
# 4. 字典工具类
在 dict.ts (opens new window) 文件中,提供了字典工具类。下面只列出方法签名与返回值,用于查阅:
// 获取 dictType 对应的字典数组,value 保持后端返回的原始值
getDictOptions(dictType: string): DictDataType[]
// 获取 dictType 对应的字典数组,value 已转换为 number
getIntDictOptions(dictType: string): NumberDictDataType[]
// 获取 dictType 对应的字典数组,value 已转换为 string
getStrDictOptions(dictType: string): StringDictDataType[]
// 获取 dictType 对应的字典数组,value 已转换为 boolean
getBoolDictOptions(dictType: string): BooleanDictDataType[]
// 获取 dictType 中值为 value 的【单个】字典对象,找不到时返回 undefined
getDictObj(dictType: string, value: any): DictDataType | undefined
// 获取 dictType 中值为 value 的字典文本,找不到时返回空字符串
getDictLabel(dictType: string, value: any): string
例如,getDictObj(DICT_TYPE.COMMON_STATUS, 0)?.label 获得状态为 0 的字典文本。
结合 Element Plus 的表单组件,完整的使用示例如下:
- 下拉框的值是字符串,使用
getStrDictOptions - 单选框的值是数字,使用
getIntDictOptions,它返回的value已经是number,直接绑定即可 - 单选框使用
el-radio-group绑定v-model,每个el-radio通过:value指定选项值
<template>
<el-form :model="formData" label-width="80px">
<!-- select 下拉框 -->
<el-form-item label="短信渠道" prop="code">
<el-select v-model="formData.code" placeholder="请选择短信渠道" clearable>
<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.SYSTEM_SMS_CHANNEL_CODE)"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<!-- radio 单选框 -->
<el-form-item label="状态" prop="status">
<el-radio-group v-model="formData.status">
<el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
:key="dict.value"
:value="dict.value"
>
{{ dict.label }}
</el-radio>
</el-radio-group>
</el-form-item>
</el-form>
</template>
<script lang="ts" setup>
import { reactive } from 'vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
const formData = reactive<{ code?: string; status?: number }>({
code: undefined,
status: undefined
})
</script>