【Nuxt】Nuxt3 解决 useFetch 首次跳转、刷新无数据的问题

函数方法

添加 await nextTick() 和 uuid (uuid 函数随便写个就行,位置也可以放在封装函数里)

const fechData = async () => {
  await nextTick()
  const data = await getNewsList(
    {
      page: paginationData.value.page,
      pageSize: paginationData.value.pageSize,
    },
    uuid()
  )
  newsList.value = data.rows
  paginationData.value.total = data.total
}
fechData()
export async function getNewsList(query: { page: number; pageSize: number }, key?: any) {
  return (await getFetchData({
    url: '/newsList',
    opts: {
      query,
    },
    method: 'get',
    key,
  })) as unknown as Res<NewsItem[]>
}

uuid 函数参考

// 产生一个随机的uuid
export const uuid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    // eslint-disable-next-line no-mixed-operators
    var r = (Math.random() * 16) | 0,
      // eslint-disable-next-line no-mixed-operators
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}

useFetch 封装

// composables/getData.ts
import type { LocationQuery } from 'vue-router'
import type { NitroFetchRequest } from 'nitropack'
import type { FetchOptions } from 'ofetch'
import { ElMessage } from 'element-plus'
// import fs from 'fs'

interface Params {
  url: NitroFetchRequest
  opts: FetchOptions<any>
  method?: 'get' | 'post' | 'put' | 'delete'
  key?: any
}

export async function getFetchData({ url, opts, method = 'get', key }: Params) {
  // 接口传参要求
  interface QueryItem {
    uid?: string
    token?: LocationQuery
  }
  const route = useRoute()
  const query: QueryItem = route.query
  console.log(key)

  const config = useRuntimeConfig()
  const { data } = await useFetch(url, {
    // 缓存key  用于缓存数据
    key,
    // method此处仅仅只处理了get与post请求
    method,
    // ofetch库会自动识别请求地址,对于url已包含域名的请求不会再拼接baseURL
    baseURL: config.public.baseURL + '',
    // onRequest相当于请求拦截
    onRequest({ request, options }) {
      // 设置请求头
      options.headers = { ...options.headers, authorization: '' }
      // 设置请求参数
      if (method === 'post') {
        options.body = { ...opts.params }
      } else {
        options.params = { ...opts.params }
      }
    },
    // onResponse相当于响应拦截
    onResponse({ response }) {
      // 处理响应数据
      // console.log(response)
    },
    onRequestError({ request, options, error }) {
      // 处理请求错误
      console.warn('request error', error)
      ElMessage.warning('Request Error')
    },
    onResponseError({ request, response, options }) {
      // 处理响应错误
      console.warn('request error', response)
      ElMessage.warning('Request Error')
    },
  })
  // 这里data本身是个ref对象,将其内部值抛出去方便调用时获得数据。
  return data.value
}

感谢

Nuxt3项目中的问题汇总-刷新页面useFetch无返回
Nuxt3数据请求及封装
nuxt3 useFetch封装一个api接口http请求 - 解决刷新页面useFetch无返回

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值