【Nuxt】发送请求

概述

以下方式只能在 setup / 生命周期钩子 里面使用。

在这里插入图片描述

useFetch

基本使用

下面的 API / hooks 具体用法查看官网文档

const BASE_URL = 'http://codercba.com:9060/juanpi/api';

// 1. $fetch  server and client
// $fetch(BASE_URL + '/homeInfo', {
//   method: 'GET'
// }).then(res => {
//   console.log(res)
// })

// 2. useAsyncData 在刷新页面时减少客户端发送的一次请求 只在 server 端发送请求
// interface HomeInfo {
//   code: number
//   data: any
// }
// const {data} = await useAsyncData<HomeInfo>('homeInfo', () => {
//   return $fetch(BASE_URL + '/homeInfo', {
//     method: 'GET'
//   })
// })
// console.log(data.value)

// 3. useAsyncData 的简写 useFetch
// const {data: dataInfo} = await useFetch(BASE_URL + '/homeInfo', {method: 'GET'});
// console.log(dataInfo.value)

// 3.1 拦截器
const {data: dataInfo} = await useFetch(BASE_URL + '/goods', {
  method: 'POST',
  // 请求拦截器
  onRequest({request, options}) {
    options.headers = {
      token: '123456'
    }
  },
  // 请求错误的拦截
  onRequestError({request, options, error}) {
    // console.log(context.error)
    console.log(error)
  },
  onResponse(context) {
    if (context.response.status === 401) {
      // 未登录
    }
  },
  onResponseError(context) {
    if (context.response.status === 401) {
      // 未登录
    }
  }
})
console.log(dataInfo.value)
const count = ref();
// 刷新 客户端不发送请求 服务端发送请求 水合后客户端可以获取请求后的数据
const {data, refresh, pending} = await useFetch(BASE_URL + '/homeInfo', {
  method: 'GET',
  body: {
    count: count
  }
});
function refreshPage() {
  // 响应式数据变化或者直接调 refresh() 都可以触发客户端的发送请求(刷新请求)
  // refresh();
  count.value++
}

封装 useFetch

// import type { AsyncData, UseFetchOptions } from 'nuxt/dist/app/composables'
import type {AsyncData, UseFetchOptions} from "#app";

const BASE_URL = 'http://codercba.com:9060/oppo-nuxt/api/'
type Methods = 'GET' | 'POST'

export interface IResultData<T> {
    code: number
    data: T
}

class MYRequest {
    request<T = any>(
        url: string,
        method: Methods,
        data?: any,
        options?: UseFetchOptions<T>
    ): Promise<AsyncData<T, Error>> {
        return new Promise((resolve, reject) => {
            const newOptions: UseFetchOptions<T> = {
                baseURL: BASE_URL,
                method: method,
                ...options
            }
            if (method === 'GET') {
                newOptions.query = data
            }
            if (method === 'POST') {
                newOptions.body = data
            }
            useFetch<T>(url, newOptions as any)
                .then((res) => {
                    resolve(res as AsyncData<T, Error>)
                })
                .catch((error) => {
                    reject(error)
                })
        })
    }

    get<T = any>(url: string, params?: any, options?: UseFetchOptions<T>) {
        return this.request<T>(url, 'GET', params, options)
    }

    post<T = any>(url: string, data?: any, options?: UseFetchOptions<T>) {
        return this.request<T>(url, 'POST', data, options)
    }
}

export default new MYRequest()

export const getHomeInfoAPI = (type: HomeInfoDataType) => {
  return myRequest.get<IResultData<IHomeInfo>>('/home/info', {
    type: type || 'oppo'
  })
}

useLazyFetch

const BASE_URL = 'http://codercba.com:9060/juanpi/api';

// // useFetch 默认会阻塞页面的导航 lazy 可以设置成 true 让其变成懒加载(不阻塞)
// const {data} = await useFetch(BASE_URL + '/homeInfo', {method: 'GET', lazy: true});
// // 确保可以获取 data
// watch(data, (newVal) => {
//   console.log(newVal)
// })

// 以上代码可以简化为
const {data} = await useLazyFetch(BASE_URL + '/homeInfo', {method: 'GET'});

onMounted(() => {
  console.log(data?.value)
})

useFetch vs axios

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值