Skip to content

字典系统 ​

字典用于管理系统中固定的枚举值,如性别、状态、类型等,避免在代码里硬编码选项。

什么是字典? ​

将硬编码的枚举值提取为可配置的数据:

typescript
// 硬编码(不推荐)
const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 2 },
];
vue
<!-- 字典(推荐):选项由后端配置,自动加载与缓存 -->
<DictSelect v-model="form.gender" code="gender" />

架构 ​

┌──────────┐     HTTP 加载      ┌──────────┐
│  前端     │ ────────────────→ │  后端     │
│ DictStore │                   │ Dict API │
│          │ ←──────────────── │          │
└──────────┘    实时推送变更     └──────────┘
      │                             │
      ▼                             ▼
┌──────────┐                  ┌──────────┐
│localStorage│                 │  MySQL   │
│ 字典缓存   │                  │ sys_dict │
└──────────┘                  └──────────┘

前端使用 ​

DictSelect 组件 ​

vue
<DictSelect v-model="form.gender" code="gender" />

DictTag 组件 ​

vue
<DictTag :model-value="row.gender" code="gender" />

编程式获取 ​

需要原始选项时使用字典 Store,同一编码的在途请求会自动合并:

typescript
import { useDictStore } from "@/stores";

const dictStore = useDictStore();
await dictStore.loadDictItems("gender");
const options = dictStore.getDictItems("gender");

组件用法与完整属性见 字典组件。

字典数据结构 ​

typescript
interface DictItemOption {
  value: number | string; // 字典值
  label: string; // 显示文本
  tagType?: "success" | "warning" | "info" | "primary" | "danger" | "";
}

字典缓存 ​

  1. 首次请求时写入 Pinia Store,并持久化到 localStorage。
  2. 同一编码只保留一个在途请求,后续读取直接命中缓存。
  3. 收到变更通知时使对应编码失效并补拉最新数据,旧响应不会回填。

实时同步 ​

后端字典变更时,通过实时通道推送 dict.changed,框架自动失效对应缓存并重新加载,页面无需手动处理:

typescript
// 收到 dict.changed 后,Store 失效该编码并通知正在展示它的页面
dictStore.invalidateDict(dictCode);

机制详见 实时通信。

后端管理 ​

数据库表 ​

sql
-- 字典类型表
CREATE TABLE sys_dict_type (
  id BIGINT PRIMARY KEY,
  dict_code VARCHAR(100) UNIQUE,
  dict_name VARCHAR(100),
  status TINYINT DEFAULT 1
);

-- 字典数据表
CREATE TABLE sys_dict_data (
  id BIGINT PRIMARY KEY,
  dict_code VARCHAR(100),
  value VARCHAR(100),
  label VARCHAR(100),
  tag_type VARCHAR(20),
  sort INT DEFAULT 0
);

字典配置 ​

在「系统管理 → 字典管理」中配置。

下一步 ​

基于 MIT 许可发布 · 如需部署协助或二开定制,请查看 支持与合作