nuxt3接口封装

本文介绍了如何在Nuxt3项目中进行接口封装,包括创建api目录、模块划分、接口文件命名规范,并展示了如何在composables中使用useApi。作者还分享了学习过程中的注意事项和期待社区反馈。

一、新建项目

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>

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

### Nuxt.js 和 Vue3封装 API 接口的示例 在 Nuxt.js 和 Vue 3封装 API 接口,通常会使用 `@nuxtjs/axios` 或者 `@nuxtjs/axios` 的替代品如 `ohmyfetch` 或 `unFetch` 等工具来简化 HTTP 请求。以下是一个完整的封装示例: #### 1. 安装依赖 首先需要安装必要的依赖包: ```bash npm install axios @nuxtjs/axios ``` #### 2. 配置 Axios 模块 在 `nuxt.config.js` 文件中添加 Axios 模块配置: ```javascript export default { modules: [&#39;@nuxtjs/axios&#39;], // 添加 Axios 模块 axios: { baseURL: &#39;https://api.example.com&#39;, // 设置全局的基础 URL timeout: 10000, // 设置请求超时时间 }, }; ``` 上述代码设置了 Axios 的基础 URL 和请求超时时间[^1]。 #### 3. 创建 API 封装文件 在项目中创建一个专门用于封装 API 的文件夹,例如 `services/api.js`,并在其中定义接口方法。 以下是封装 API 的示例代码: ```javascript // services/api.js import { $fetch } from &#39;ohmyfetch&#39;; // 使用 ohmyfetch 替代 Axios(可选) const apiClient = (url, options) => { const headers = { &#39;Content-Type&#39;: &#39;application/json&#39;, Authorization: `Bearer ${localStorage.getItem(&#39;token&#39;)}`, // 动态添加 Token }; return $fetch(url, { ...options, headers }).catch((error) => { console.error(&#39;API Error:&#39;, error.message); throw error; }); }; // 封装 GET 请求 export const fetchItems = async () => { return await apiClient(&#39;/items&#39;, { method: &#39;GET&#39; }); }; // 封装 POST 请求 export const createItem = async (data) => { return await apiClient(&#39;/items&#39;, { method: &#39;POST&#39;, body: data }); }; // 封装 PUT 请求 export const updateItem = async (id, data) => { return await apiClient(`/items/${id}`, { method: &#39;PUT&#39;, body: data }); }; // 封装 DELETE 请求 export const deleteItem = async (id) => { return await apiClient(`/items/${id}`, { method: &#39;DELETE&#39; }); }; ``` 以上代码通过 `$fetch` 或 Axios 封装了常见的 HTTP 请求方法,并动态添加了请求头中的 Token[^4]。 #### 4. 在组件中使用封装的 API 在 Vue 组件或页面中可以直接调用封装好的 API 方法。例如: ```vue <template> <div> <button @click="loadItems">加载数据</button> <ul> <li v-for="item in items" :key="item.id">{{ item.name }}</li> </ul> </div> </template> <script> import { fetchItems } from &#39;~/services/api&#39;; export default { data() { return { items: [], }; }, methods: { async loadItems() { try { this.items = await fetchItems(); } catch (error) { console.error(&#39;Failed to fetch items:&#39;, error.message); } }, }, }; </script> ``` 此代码展示了如何在组件中调用封装的 API 方法并处理返回的数据[^2]。 #### 5. 处理错误和状态管理 如果需要更复杂的错误处理或状态管理,可以结合 Vuex 或 Pinia 来实现。例如,在 Pinia 中定义一个 store 来管理 API 状态: ```javascript // stores/apiStore.js import { defineStore } from &#39;pinia&#39;; export const useApiStore = defineStore(&#39;api&#39;, { state: () => ({ loading: false, error: null, }), actions: { async fetchData() { this.loading = true; this.error = null; try { const response = await fetchItems(); console.log(&#39;Data fetched:&#39;, response); } catch (error) { this.error = error.message; } finally { this.loading = false; } }, }, }); ``` 然后在组件中引入并使用该 store。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值