Skip to content

DictSelect、DictTag 与 useDict

Forge 强制使用字典组件管理下拉选项和状态标签。你在开发中禁止硬编码 options,必须使用字典组件。

字典数据流

后端 sys_dict_type + sys_dict_data 表

GET /system/dict/data/type/{dictType}

前端 useDict('dict_type') 加载缓存

DictSelect / DictTag 渲染

useDict

获取字典数据的组合式函数:

javascript
import { useDict } from '@/composables/useDict'

const { dict } = useDict('biz_order_status')

// dict.value.biz_order_status 是数组
// [{ dictLabel: '待支付', dictValue: '0', listClass: 'warning' }, ...]

DictSelect

字典下拉选择器,用于表单中的下拉选项:

vue
<template>
  <DictSelect v-model:value="form.status" dict-type="biz_order_status" />
</template>

<script setup>
import DictSelect from '@/components/DictSelect.vue'

const form = reactive({ status: '' })
</script>

在 AiCrudPage schema 中使用:

javascript
const schema = computed(() => [
  {
    field: 'status',
    label: '状态',
    component: 'DictSelect',
    dictType: 'biz_order_status'
  }
])

DictTag

字典标签渲染,用于表格中显示状态标签(自动映射颜色):

vue
<template>
  <DictTag :value="row.status" dict-type="biz_order_status" />
</template>

<script setup>
import DictTag from '@/components/DictTag.vue'
</script>

在 AiCrudPage schema 中使用:

javascript
const schema = computed(() => [
  {
    field: 'status',
    label: '状态',
    component: 'DictTag',
    dictType: 'biz_order_status'
  }
])

自定义字典类型

1. 后端添加字典

通过 Flyway 脚本添加字典类型:

sql
-- 字典类型
INSERT INTO sys_dict_type (id, dict_name, dict_type, tenant_id)
SELECT NULL, '订单状态', 'biz_order_status', 1
WHERE NOT EXISTS (
    SELECT 1 FROM sys_dict_type WHERE dict_type = 'biz_order_status' AND tenant_id = 1
);

-- 字典数据
INSERT INTO sys_dict_data (dict_sort, dict_label, dict_value, dict_type, list_class, tenant_id)
SELECT 1, '待支付', '0', 'biz_order_status', 'warning', 1
WHERE NOT EXISTS (
    SELECT 1 FROM sys_dict_data WHERE dict_type = 'biz_order_status' AND dict_value = '0' AND tenant_id = 1
);

2. 前端使用

javascript
// 字典类型命名:小写下划线,业务前缀
useDict('biz_order_status')

字典命名规范

规则示例
小写下划线biz_order_status
系统级用 sys_ 前缀sys_user_sex
文件存储类型sys_file_storage_type
业务字典用业务前缀biz_order_status

dict_value 一致性

dict_value 必须与后端枚举/存储值保持一致:

sql
-- 后端 status 字段值为 '0'、'1'、'2'
-- 字典 dict_value 也必须是 '0'、'1'、'2'
dict_value = '0'  -- 待支付
dict_value = '1'  -- 已支付
dict_value = '2'  -- 已取消

Schema 必须用 computed

javascript
// 正确:computed 确保字典异步加载后响应式更新
const schema = computed(() => [
  { field: 'status', label: '状态', component: 'DictSelect', dictType: 'biz_order_status' }
])

// 禁止:普通对象,字典异步加载后不更新
const schema = [
  { field: 'status', label: '状态', component: 'DictSelect', dictType: 'biz_order_status' }
]

禁止事项

  • 禁止在前端页面硬编码 options 数组
  • 禁止在标签映射中写死 if (status === '0') return '待支付'
  • 禁止使用固定 0/1 配合唯一索引(删除后用主键值)
  • 新增内置字典必须通过 Flyway 脚本,tenant_id 必须为 1

Forge Admin — 基于 Vue3 + Spring Boot 的企业级后台管理框架