Nuxt3踩坑之useFetch和useLazyFetch

Snipaste_20230328_152138.jpg

前言

之前在学习Nuxt3的过程中,被useFetch和useLazyFetch搞了 意想不到的久,秉承着用他内置api的原理,我也没去用axios请求。

说说useFetch

useFetch其实很简单,就是简单的请求,参数啥的可以去官网文档查阅。 官网useFetch链接

那么useFetch就是一个普通的Fetch的请求。

          
  • 1
  • 2
  • 3
  • 4
//官网例子 const { data, pending, error, refresh } = await useFetch('https://api.nuxtjs.dev/mountains',{ pick: ['title'] })

当nuxt3中使用的时候,用上述await会阻塞路由的进行,也就是我从首页跳到其他页面时,页面会在请求完成时才渲染出来,看效果的可以给接口加个延迟试试。

其实这个效果一般不是我们想要,通常我们需要的是先让页面出来,也就是所谓的先导航,再数据请求,然后上个骨架屏之类的。

那么nuxt3提供了一个useLazyFetch。

useLazyFetch

useLazyFetch提供了一个围绕useFetch的包装器,通过将lazy选项设置为true,在解析处理程序之前触发导航

这是一个特别难受的api,他主要的功能就是所谓我上面说的先导航再请求。

官网的例子

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
<template> <div v-if="pending"> Loading ... </div> <div v-else> <div v-for="post in posts"> <!-- do something --> </div> </div> </template> <script setup> /* Navigation will occur before fetching is complete. Handle pending and error states directly within your component's template */ const { pending, data: posts } = useLazyFetch('/api/posts') watch(posts, (newPosts) => { // Because posts starts out null, you won't have access // to its contents immediately, but you can watch it. }) </script>

说的很清楚路由不会阻塞,但是先给的data为null,需要用watch去监听。所以麻烦就是处理这个null的问题。

下面是我在composables中直接写了一个use的方法**(下面是我傻了的错误示范,写了个useLazyrequest本身就是异步了当然先路由了)**

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
// 不阻塞路由方案 先路由进页面再请求数据 需要watch处理null的情况 import http from '@/utils/http' export const useLazyrequest = async (url: string, method: string, callback: (ndata: any, pending: any) => void, params?: any, options?: any) => { const { data, pending }: any = await http.request(url, method, 1, params, options) watch(data, (v: any) => { if (v && v.code === 0) { const ndata = v.data callback(ndata, pending) } else { // 提示出错 } }, { immediate: true }) }

因为也是刚学useLazyFetch我还并没有找到用途。

解决先路由再请求问题

那么其实先路由再请求的方案就是用useFetch然后去.then就好了。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
useFetch('https://kedong.me/api_test/comment', { method: 'GET', }).then(({ data }) => { console.log(data.value.data) comments.value = data.value.data.comments count.value = data.value.data.count pending.value = false })

想要拿到全部数据后显示那就用await。

注意

在跳转路由后,如果要用localStorage处理数据,可以在onUpdated处理。因为异步会在onMounted后获取到数据。

总结

先路由就用useFetch.then 先把数据获取了再跳转可以用 await useFetch 在nuxt3基本上用useFetch就行。用useLazyFetch +await记得处理data null的情况。

(完)
无锡踏青
一次着急的旅行
双指针: 有序数组的 Two Sum(167)
在有序数组中找出两个数,使它们的和为 target。
再谈浅拷贝和深拷贝
基础要扎实
小程序获取街道等其他地址信息
运用腾讯位置服务sdk处理更多地图信息
React hooks的几个demo
忘了?没关系看demo
请求加薪失败!
谈谈公司和工作
等待你的评论