Skip to content

9.13 API 模块编写规范 ​

概述

本节定义前端 API 模块的编写规范,包括命名规范、请求方式和文件组织。

命名规范 ​

类型规范示例
文件名小驼峰,与后端模块对应example.ts
查询函数get{Module}Page / get{Module}List / get{Module}DetailgetExamplePage
新增函数{module}AddexampleAdd
修改函数{module}UpdateexampleUpdate
删除函数{module}Delete / {module}BatchDeleteexampleDelete
导入函数{module}ImportexampleImport
导出函数{module}ExportexampleExport

请求方式 ​

操作HTTP 方法参数传递说明
查询GETparams(URL 参数)分页/列表/详情
新增POSTdata(请求体)JSON 格式
修改PUTdata(请求体)JSON 格式,含 id
删除DELETEURL 参数或 data单条用 URL,批量用 data

文件组织 ​

text
ui/src/api/
├── common/index.ts         # 公共接口(字典、验证码、菜单等)
├── index.ts                # 全局接口(登录、登出、刷新Token)
├── system/                 # 系统管理模块
│   ├── user.ts
│   ├── role.ts
│   ├── menu.ts
│   ├── dept.ts
│   ├── position.ts
│   └── level.ts
├── content/                # 内容管理模块
│   ├── article.ts
│   ├── category.ts
│   └── link.ts
└── tool/                   # 工具模块
    └── example.ts

标准模板 ​

typescript
// ui/src/api/tool/example.ts
import { http } from '@/utils/http/axios';

// 分页查询
export function getExamplePage(params?) {
  return http.request({ url: '/example/page', method: 'GET', params });
}

// 全量列表
export function getExampleList(params?) {
  return http.request({ url: '/example/list', method: 'GET', params });
}

// 详情
export function getExampleDetail(id) {
  return http.request({ url: '/example/detail/' + id, method: 'GET' });
}

// 新增
export function exampleAdd(data: any) {
  return http.request({ url: '/example/add', method: 'POST', data });
}

// 修改
export function exampleUpdate(data: any) {
  return http.request({ url: '/example/update', method: 'PUT', data });
}

// 删除
export function exampleDelete(id) {
  return http.request({ url: '/example/delete/' + id, method: 'DELETE' });
}

// 批量删除
export function exampleBatchDelete(data: any) {
  return http.request({ url: '/example/batchDelete', method: 'DELETE', data });
}

常见扩展操作 ​

操作函数名示例HTTP 方法
重置密码userResetPwd(data)POST
导入{module}Import(data: FormData)POST(multipart/form-data)
导出{module}Export(params)GET
刷新缓存dictRefreshCache()GET
获取菜单getMenus()GET
获取字典项getDictItemList(code)GET

组件中使用 ​

vue
<script setup lang="ts">
import { getExamplePage, exampleDelete } from '@/api/tool/example';
import { ElMessage, ElMessageBox } from 'element-plus';

const tableData = ref([]);

// 查询
const fetchData = async () => {
  const res = await getExamplePage({ pageNo: 1, pageSize: 20 });
  tableData.value = res.records;
};

// 删除
const handleDelete = async (id) => {
  await ElMessageBox.confirm('确认删除?', '提示', { type: 'warning' });
  await exampleDelete(id);
  ElMessage.success('删除成功');
  fetchData();
};
</script>

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