在 composables 中创建 HTTP 请求封装

在 composables 目录下创建一个文件,比如 useHttp.ts:

import { useFetch } from 'nuxt/app';

function request(url: string, method: string, data?: any, headers?: any) {
  const options: any = {
    method,
    headers: {
    Authorization: 'Bearer your-token',
    ...headers,
  },
  onResponse({ response }) {
    // 处理响应
  },
  onRequestError({ request, options, error }) {
    // 处理请求错误
  },
  onResponseError({ request, response, options }) {
    // 处理响应错误
  },
  };

  if (method === 'GET' || method === 'DELETE') {
    options.params = data;
  } else {
    options.body = data;
  }

  return useFetch(url, options);
}

export function useGet(url: string, data?: any, headers?: any) {
  return request(url, 'GET', data, headers);
}

export function usePost(url: string, data?: any, headers?: any) {
  return request(url, 'POST', data, headers);
}

export function usePut(url: string, data?: any, headers?: any) {
  return request(url, 'PUT', data, headers);
}

export function useDel(url: string, data?: any, headers?: any) {
  return request(url, 'DELETE', data, headers);
}

在组件或页面中使用

你可以在组件或页面中引入并使用这些封装好的请求函数。例如:

import { useGet, usePost, usePut, useDel } from '~/composables/useHttp';

export default defineComponent({
  async setup() {
    // GET 请求
    const { data: getData, error: getError } = await useGet('/api/endpoint', { param1: 'value1' });

    // POST 请求
    const { data: postData, error: postError } = await usePost('/api/endpoint', { key: 'value' });

    // PUT 请求
    const { data: putData, error: putError } = await usePut('/api/endpoint/1', { key: 'newValue' });

    // DELETE 请求
    const { data: delData, error: delError } = await useDel('/api/endpoint/1');

    return {
      getData,
      postData,
      putData,
      delData,
      getError,
      postError,
      putError,
      delError,
    };
  },
});

解释

  1. Composable 的封装

• 将请求逻辑封装在 composables 中,使得这些函数可以在整个应用中被复用。

• 通过 useGet、usePost、usePut、useDel 函数来调用相应的 HTTP 请求。

  1. 使用方式一致

• 这种封装方式与之前在 utils 中实现的方法一致,只不过放在 composables 中,更符合 Nuxt 3 的设计理念,方便组合使用。

  1. 响应式数据

• useFetch 返回响应式的数据,可以在组件中直接使用,响应式数据会自动更新页面。