nuxt fetch $fetch useFetch 等使用方式区别

186 阅读1分钟

大概记录自己使用时的疑惑

fetch 用于server api的代理请求 属于服务器端的请求 官方apis: nuxt.com/docs/4.x/ge…

// 文件是在 server/api 目录下
const response = await fetch('https://www.otter-data.com/api/blogsList', {
        cache: "no-cache", //不缓存
    })
const json = await response.json()
return json

$fetch 用于客户端用户发起请求

例如 用户点击后需要刷新列表 官方介绍: nuxt.com/docs/4.x/ap…

//app/pages/blogs/index.vue
const refresh = () => {
  const {data} = await $fetch('https://www.otter-data.com/api/blogsList', {
    method: 'GET',
    credentials: "include",
  })
  console.log('list:', data.value)
}

useFetch 页面加载时 如果需要预渲染那么就用它 还有个 useAsyncFetch也可以

如果想在服务端渲染文章而不是在客户端

官方介绍: nuxt.com/docs/4.x/ap…


const {data} = await useFetch('https://www.otter-data.com/api/blogsList', {
    method: 'GET',
    credentials: "include",
  })

useAsyncFetch 和 useFetch 个人感觉没什么区别,只是增加了更细的控制 组合 $fetch使用 例如: 自定义缓存key, 是否在服务端进行发送请求, 是否监听参数改变发起请求等参数

官方说明: nuxt.com/docs/4.x/ap…

我只是在文章详情使用,因为需要缓存,同时不能因为缓存导致内容变更却未生效问题

const { data } = await useAsyncData(`article-${uuid}`, () =>
    $fetch(`/api/detail?article_id=1}`, {
      method: 'GET',
      credentials: 'include',
    })
)