在Vue3前端项目中,高效管理API接口是提升开发效率的关键。本文将介绍一种优雅的API基础封装方案------getBaseApi
方法,它可以通过单次配置生成完整的CRUD接口模板,显著减少重复代码并强化类型安全。
设计目标
- 标准化接口规范:统一接口路径与方法命名
- 类型安全:通过TypeScript泛型支持自定义数据类型
- 灵活扩展:允许不同模块覆盖默认参数类型
- 开箱即用:5秒生成完整CRUD接口集合
apis目录结构
js
apis
--user
--index.ts
--type.ts
--dept
--index.ts
--type.ts
js
// @/apis/user/index.ts
import type * as T from './type'
import { getBaseApi } from '@/apis/base'
import http from '@/utils/http'
export type * from './type'
/** 用户模块 */
export const baseAPI = getBaseApi<T.ListItem>({ baseUrl: '/user' })
// 其他接口
export const getUserRoleList = (params: { id: string }) => {
return http.get<PageRes<T.UserRoleListItem[]>>('/user/getUserRoleList', params)
}
js
// @/apis/user/type.ts
export interface ListItem {
id: string
name: string
account: string
avatar: string
gender: Gender
phone: string
email: string
createTime: string
address: string
proportion: number
status: Status
hobbys: string[]
}
export interface UserRoleListItem { ... }
上面代码没有使用export default,是因为对Tree Shaking不友好
使用
js
import { baseAPI, getUserRoleList } from '@/apis/user'
import type * as T from '@/apis/user' // 获取类型
const userList = ref<T.ListItem[]>([])
// 获取列表
baseAPI.getList({ page: 1, size: 10 })
// 获取详情
baseAPI.getDetail({ id: 'xxx' })
// 新增
baseAPI.add(formData)
// 编辑
baseAPI.update(formData)
// 删除
baseAPI.delete({ ids: ['xx1', 'xx2'] })
使用baseAPI都会有类型提示


类型覆盖

核心代码解析
js
interface DefaultP {
GetListParams?: Record<string, any> // 分页查询参数
GetDetailParams?: { id: string } // 详情查询参数
AddParams?: Record<string, any> // 新增参数
UpdateParams?: Record<string, any> // 更新参数
DeleteParams?: { ids: string[] } // 删除参数
}
export function getBaseApi<T, P extends DefaultP = DefaultP>(
params: { baseUrl: string }
) {
const { baseUrl } = params;
return {
// 获取分页列表
getList(params?: P['GetListParams']) {
return http.get<PageRes<T[]>>(`${baseUrl}/getList`, params)
},
// 获取详情
getDetail(params: P['GetDetailParams']) {
return http.get<T>(`${baseUrl}/getDetail`, params)
},
// 新增数据
add(params: P['AddParams']) {
return http.post<T>(`${baseUrl}/add`, params)
},
// 修改数据
update(params: P['UpdateParams']) {
return http.post<T>(`${baseUrl}/update`, params)
},
// 批量删除
delete(params: P['DeleteParams']) {
return http.post<boolean>(`${baseUrl}/delete`, params)
}
}
}
T
:定义核心数据类型
P
:继承默认参数类型DefaultP
,允许模块自定义参数结构