Skip to content

8.5 字典数据接口 ​

概述

字典数据接口分为两组:字典管理(DictController)和字典项管理(DictItemController)。前端通过字典编码获取字典项列表用于下拉框,后台通过管理接口维护字典数据。

接口总览 ​

字典管理(DictController) ​

方法URL权限码说明
GET/api/dict/pagesys:dict:page字典分页列表
GET/api/dict/detail/{id}sys:dict:detail字典详情
POST/api/dict/addsys:dict:add添加字典
PUT/api/dict/updatesys:dict:update修改字典
DELETE/api/dict/delete/{id}sys:dict:delete删除字典
DELETE/api/dict/batchDeletesys:dict:batchDelete批量删除字典
GET/api/dict/refreshCachesys:dict:update刷新字典缓存

字典项管理(DictItemController) ​

方法URL权限码说明
GET/api/dict/item/pagesys:dict:page字典项分页列表
GET/api/dict/item/detail/{id}sys:dict:detail字典项详情
POST/api/dict/item/addsys:dict:add添加字典项
PUT/api/dict/item/updatesys:dict:update修改字典项
DELETE/api/dict/item/delete/{id}sys:dict:delete删除字典项
DELETE/api/dict/item/batchDeletesys:dict:batchDelete批量删除字典项
GET/api/dict/item/getDictItemList/{code}—按编码获取字典项列表

按编码获取字典项(最常用) ​

接口信息 ​

项目说明
URLGET /api/dict/item/getDictItemList/{code}
权限无需额外权限(已登录即可)
用途前端下拉框数据源

请求示例 ​

bash
GET /api/dict/item/getDictItemList/gender
Authorization: Bearer <token>

成功响应 ​

json
{
    "code": 0,
    "ok": true,
    "msg": "操作成功",
    "data": [
        { "id": 1, "name": "男", "value": "1", "sort": 1, "note": "" },
        { "id": 2, "name": "女", "value": "2", "sort": 2, "note": "" }
    ]
}

响应字段 ​

字段类型说明
idnumber字典项 ID
namestring字典项名称(显示标签)
valuestring字典项值(存储值)
sortnumber排序
notestring备注

常用字典编码 ​

编码说明字典项
gender性别1=男, 2=女
user_status用户状态0=禁用, 1=启用
article_status文章状态0=草稿, 1=已发布
tenant_status租户状态0=禁用, 1=启用
notice_type通知类型1=通知, 2=公告
example_type案例类型1=基础, 2=进阶, 3=高级
example_status案例状态0=禁用, 1=启用
data_scope数据权限1=全部, 2=本部门, 3=仅本人

刷新字典缓存 ​

项目说明
URLGET /api/dict/refreshCache
权限sys:dict:update
演示环境允许执行(标注 #[DemoAllow])

修改字典数据后需调用此接口刷新缓存,否则新数据不会立即生效。

bash
GET /api/dict/refreshCache
Authorization: Bearer <token>

响应:

json
{
    "code": 0,
    "ok": true,
    "msg": "缓存已刷新",
    "data": null
}

前端使用 ​

获取字典项 ​

typescript
// ui/src/api/common/index.ts
export function getDictItemList(code: string) {
  return http.request({
    url: '/dict/item/getDictItemList/' + code,
    method: 'GET',
  });
}

下拉框使用 ​

vue
<template>
  <el-select v-model="formData.status" placeholder="请选择状态">
    <el-option
      v-for="item in statusOptions"
      :key="item.value"
      :label="item.name"
      :value="item.value"
    />
  </el-select>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getDictItemList } from '@/api/common/index';

const statusOptions = ref([]);

onMounted(async () => {
  statusOptions.value = await getDictItemList('example_status');
});
</script>

多个字典批量获取 ​

typescript
const [genderOptions, statusOptions] = await Promise.all([
  getDictItemList('gender'),
  getDictItemList('user_status'),
]);

封装为通用 Hook ​

typescript
// ui/src/hooks/web/useDict.ts
import { ref, onMounted } from 'vue';
import { getDictItemList } from '@/api/common/index';

export function useDict(code: string) {
  const options = ref([]);
  const loading = ref(false);

  const load = async () => {
    loading.value = true;
    try {
      options.value = await getDictItemList(code);
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => load());

  return { options, loading, reload: load };
}

// 使用
const { options: genderOptions } = useDict('gender');
const { options: statusOptions } = useDict('user_status');

枚举显示名自动翻译 ​

Logic 中配置 serializeMaps 后,查询数据自动补全 {字段名}Text:

php
/**
 * 枚举显示名映射
 *
 * @var array
 */
protected array $serializeMaps = [
    'status' => 'example_status',
];
json
// API 响应自动包含 statusText
{ "id": 1, "name": "测试", "status": 1, "statusText": "启用" }

缓存机制

DictService 采用两级缓存(请求级 + 持久缓存,1小时过期)。修改字典数据后需调用刷新缓存接口,否则新数据不会立即生效。

后端 DictService 调用 ​

php
use app\service\DictService;

// 根据值获取名称
$text = DictService::getText('gender', 1);  // '男'

// 根据名称反向获取值
$value = DictService::getValue('gender', '男');  // '1'

// 获取下拉框选项
$options = DictService::getOptions('gender');
// [['label'=>'男','value'=>'1'], ['label'=>'女','value'=>'2']]

// 获取完整字典项(含 id、sort、note)
$items = DictService::getFullItems('gender');

// 清除缓存
DictService::clearCache('gender');    // 清除指定字典
DictService::clearAllCache();         // 清除所有字典

小蚂蚁云团队 · 提供技术支持