nuxt3接口封装

一、新建项目

npx nuxi@latest init my-app

二、完善项目目录

根据 Nuxt 官方文档,并结合项目实际情况完善项目相关目录

因为该项目仅用于演示在 Nuxt3 中接口的封装,所以在此只添加了与接口封装相关的 2 个文件目录

image.png

三、接口封装

  1. 在 api 目录下新建 modulesapi.tsindex.ts

    image.png

    // modules
    
    * 该目录中存放项目所有接口文件
    * 该目录中的文件层级不限,可按照任意模式划分目录结构,但接口文件名称需统一设为 `*.ts`,且接口文件名称不可重复
    
    例:可按接口类型划分目录结构
      modules
      ├─ get
      │   ├─ a.ts
      │   ├─ b.ts
      ├─ post
      │   ├─ c.ts
      ├─ put
      │   ├─ d.ts
      ├─ delete
      │   ├─ e.ts
    
    例:可按项目模块划分目录结构
      modules
      ├─ access
      │   ├─ login.ts
      │   ├─ logout.ts
      ├─ list.ts
    
    
    // modules/list.ts
    
    import $api from "@/api/api";
    
    export default {
      listGet: (id: number) => {return $api(`/list/${id}`, { method: `get` })},
      listPost: (body: any) => {return $api(`/list`, { method: `post`, body })},
      listPut: (id: number, body: any) => {return $api(`/list/${id}`, { method: `put`, body })},
      listDelete: (body: any) => {return $api(`/list`, { method: `delete`, body })},
    };
    
    // api.ts
    
    const $api = $fetch.create({
      // 请求拦截
      onRequest(req) {
        // 请求拦截相关配置
      },
    
      // 请求错误拦截
      onRequestError(reqErr) {
        // 请求错误拦截相关配置
      },
    
      // 响应拦截
      onResponse(res) {
        // 响应拦截相关配置
      },
    
      // 响应错误拦截
      onResponseError(resErr) {
        // 响应错误拦截相关配置
        console.table(resErr);
      },
    });
    
    export default $api;
    
    
    // index.ts
    // 获取 modules 目录下文件名格式为 `*.ts` 的文件并导出
    
    const modulesFiles: Record<string, any> = import.meta.glob("./modules/**/*.ts", { eager: true });
    
    let modules: Record<string, any> = {};
    
    for (const modulePath in modulesFiles) {
      const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1").split("/").pop();
      modules[moduleName || ''] = modulesFiles[modulePath].default;
    }
    
    export default modules;
    
    
  2. 在 composables 目录下新建 useApi.ts

    image.png

    // useApi.ts
    
    import api from "@/api/index";
    
    export const useApi = () => api;
    
    

至此,接口封装完成,可以在页面中使用了,使用示例如下:

// pages/index.ts

<template>
  <div>
    
  </div>
</template>

<script setup lang="ts">
const list = () => {
  const id = 1;
  useApi().list.listGet(id).then(res => {console.log(res)})
}
</script>

<style scoped>

</style>

坑是踩不完的,学如逆水行舟,不进则退。如有不完善或错误的地方请大家指正,大家共同进步!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值