Skip to content

数据字典

概述

数据字典模块(dictStore)统一管理项目中的所有枚举数据(如状态、性别、类型等)。数据由「字典管理」页面维护,运行时按 dict_type 动态分组构建,提供三个核心方法:options()label()tag()

使用方式

options(type) — 获取下拉选项

返回指定字典类型的选项数组,可直接用于 NSelectoptions 属性:

vue
<script setup lang="ts">
import { useDictStore } from '@/stores/dict'

const dictStore = useDictStore()

// 获取状态选项
const statusOptions = dictStore.options('common_status')
// => [{ label: '启用', value: 1 }, { label: '禁用', value: 0 }]
</script>

<template>
  <NSelect :options="statusOptions" v-model:value="form.status" />
</template>

label(type, val) — 值转文案

将字典值转换为显示文案:

typescript
const dictStore = useDictStore()

// 状态值 1 转为 "启用"
const text = dictStore.label('common_status', 1)
// => "启用"

// 状态值 0 转为 "禁用"
const disabledText = dictStore.label('common_status', 0)
// => "禁用"

在表格列中使用:

typescript
const columns = [
  {
    title: '状态',
    key: 'status',
    render: (row) => dictStore.label('common_status', row.status),
  },
]

tag(type, val) — 渲染标签

将字典值渲染为带颜色的 NTag 组件:

typescript
const columns = [
  {
    title: '状态',
    key: 'status',
    render: (row) => dictStore.tag('common_status', row.status),
  },
]

渲染效果:

  • 启用 → 绿色标签
  • 禁用 → 红色标签

自定义标签颜色

字典数据支持配置标签颜色,在字典管理页面为每个字典项设置 tagType

jsonc
// 字典数据示例
{
  "dict_type": "common_status",
  "items": [
    { "label": "启用", "value": 1, "tagType": "success" },
    { "label": "禁用", "value": 0, "tagType": "error" }
  ]
}

tagType 支持 Naive UI 的 Tag 类型:defaultinfosuccesswarningerror

数据加载时机

字典数据在用户登录成功、加载菜单后自动拉取。如需在登录前使用字典数据,需手动调用 dictStore.fetchDicts() 加载。

最佳实践

状态、性别、类型等枚举值始终通过 dictStore 获取,不要在页面中内联写死选项。这样当后端修改字典项时,前端自动生效,无需改代码。

Released under the MIT License.