Vue项目统一管理Api

231 阅读1分钟

一、优点

  1. 代码结构清晰:将所有的API请求集中管理,可以让项目的代码结构更加清晰,方便开发人员阅读和维护。
  2. 提高开发效率:通过统一管理API,可以减少重复的代码编写,提高开发效率,减少出错的可能性。
  3. 更好的团队协作:通过统一管理API,可以让团队成员更好地协作,减少沟通成本,提高团队整体的开发效率。

二、改造步骤

  1. 在src下面创建一个单独的目录来管理所有的API请求,命名为api;
  2. 在这个文件或目录中,定义所有的API请求,按照模块或功能进行分类,例如用户模块、商品模块等;
├─ src
│  ├─ api
│  │  ├─ index.ts
│  │  ├─ life-color.ts
│  │  ├─ saying.ts
│  │  ├─ system.ts
│  │  ├─ tag.ts
│  │  └─ website.ts
  1. 在api文件中新建index.ts文件,用于统一各个模块的api进行输出;
import * as sayingApi from './saying'
import * as lifeColorApi from './life-color'
import * as systemApi from './system'
import * as tagApi from './tag'
import * as websiteApi from './website'

export {
  sayingApi,
  lifeColorApi,
  systemApi,
  tagApi,
  websiteApi
}
  1. 方法调用
import { websiteApi } from '@/api'

const res = await websiteApi.getWebsite(pageParam.value)