useFetch

通过支持 SSR 的可组合函数从 API 端点获取数据。

此可组合函数为 useAsyncData$fetch 提供了一个便捷的包装器。 它会根据 URL 和获取选项自动生成一个键,为基于服务器路由的请求 URL 提供类型提示,并推断 API 响应类型。

useFetch 是一个旨在直接在 setup 函数、插件或路由中间件中调用的可组合函数。它返回响应式可组合函数,并处理将响应添加到 Nuxt 载荷中,以便在页面水合时从服务器传递到客户端,无需在客户端重新获取数据

使用

pages/modules.vue
<script setup lang="ts">
const { data, status, error, refresh, clear } = await useFetch('/api/modules', {
  pick: ['title']
})
</script>
如果您使用自定义的 useFetch 包装器,请勿在可组合函数中对其使用 await,因为这可能导致意外行为。请参阅此方法以了解如何创建自定义异步数据获取器。
datastatuserror 是 Vue ref,在 <script setup> 中使用时需要通过 .value 访问,而 refresh/executeclear 是普通函数。

通过 query 选项,您可以为查询添加搜索参数。此选项扩展自 unjs/ofetch,并使用 unjs/ufo 创建 URL。对象会被自动序列化。

const param1 = ref('value1')
const { data, status, error, refresh } = await useFetch('/api/modules', {
  query: { param1, param2: 'value2' }
})

上述示例将生成 https://api.nuxt.com/modules?param1=value1¶m2=value2

您还可以使用拦截器

const { data, status, error, refresh, clear } = await useFetch('/api/auth/login', {
  onRequest({ request, options }) {
    // 设置请求头
    // 请注意,这依赖于 ofetch >= 1.4.0 - 您可能需要刷新您的锁文件
    options.headers.set('Authorization', '...')
  },
  onRequestError({ request, options, error }) {
    // 处理请求错误
  },
  onResponse({ request, response, options }) {
    // 处理响应数据
    localStorage.setItem('token', response._data.token)
  },
  onResponseError({ request, response, options }) {
    // 处理响应错误
  }
})

Reactive Keys and Shared State

You can use a computed ref or a plain ref as the URL, allowing for dynamic data fetching that automatically updates when the URL changes:

pages/[id].vue
<script setup lang="ts">
const route = useRoute()
const id = computed(() => route.params.id)

// When the route changes and id updates, the data will be automatically refetched
const { data: post } = await useFetch(() => `/api/posts/${id.value}`)
</script>

When using useFetch with the same URL and options in multiple components, they will share the same data, error and status refs. This ensures consistency across components.

useFetch 是编译器转换的保留函数名,因此您不应将自己的函数命名为 useFetch
如果您从 useFetch 解构的 data 变量返回一个字符串而不是 JSON 解析的对象,请确保您的组件未包含类似 import { useFetch } from '@vueuse/core' 的导入语句。

阅读并编辑实时示例中的内容 Docs > Examples > Advanced > Use Custom Fetch Composable.
阅读更多 Docs > Getting Started > Data Fetching.
阅读并编辑实时示例中的内容 Docs > Examples > Features > Data Fetching.

参数

  • URL:要获取的 URL。
  • Options(扩展自 unjs/ofetch 选项和 AsyncDataOptions):
    • method:请求方法。
    • query:使用 ufo 为 URL 添加查询搜索参数。
    • paramsquery 的别名。
    • body:请求体——如果传入对象,会自动序列化。
    • headers:请求头。
    • baseURL:请求的基 URL。
    • timeout:自动中止请求的毫秒数。
    • cache:根据 Fetch API 处理缓存控制。
      • 您可以传递布尔值禁用缓存,或者传递以下值之一:defaultno-storereloadno-cacheforce-cacheonly-if-cached
所有 fetch 选项都可以接受 computedref 值。这些值会被监听,如果更新,将自动使用新值发起新请求。
  • Options(来自 useAsyncData):
    • key:一个唯一键,确保跨请求的数据获取能够正确去重。如果未提供,将根据 URL 和 fetch 选项自动生成。
    • server:是否在服务器端获取数据(默认为 true)。
    • lazy:是否在路由加载后解析异步函数,而不是阻塞客户端导航(默认为 false)。
    • immediate:当设置为 false 时,将阻止请求立即触发(默认为 true)。
    • default:一个工厂函数,用于在异步函数解析前设置 data 的默认值——在 lazy: trueimmediate: false 选项下很有用。
    • transform:一个函数,可用于在解析后修改 handler 函数的结果。
    • getCachedData:提供一个返回缓存数据的函数。返回 nullundefined 将触发获取。默认值为:
      const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating 
        ? nuxtApp.payload.data[key] 
        : nuxtApp.static.data[key]
      
      仅当 nuxt.configexperimental.payloadExtraction 启用时才缓存数据。
    • pick:仅从 handler 函数结果中选择此数组中指定的键。
    • watch:监听一组响应式源,当它们更改时自动刷新获取结果。默认情况下,fetch 选项和 URL 会被监听。您可以通过 watch: false 完全忽略响应式源。结合 immediate: false,可以实现完全手动的 useFetch。(您可以在此处查看使用 watch 的示例。)
    • deep:以深层 ref 对象返回数据。默认为 false,以浅层 ref 对象返回数据以提升性能。
    • dedupe:避免同一键同时多次获取(默认为 cancel)。可能的选项:
      • cancel - 发起新请求时取消现有请求。
      • defer - 如果有待处理的请求,则完全不发起新请求。
如果您将函数或 ref 作为 url 参数,或者将函数作为 options 参数的实参,那么即使选项看似相同,useFetch 调用也不会与其他代码库中的 useFetch 调用匹配。如果您希望强制匹配,可以在 options 中提供自己的键。
如果您在开发环境中使用 useFetch 调用(外部)带有自签名证书的 HTTPS URL,您需要在环境中设置 NODE_TLS_REJECT_UNAUTHORIZED=0

返回值

  • data:传入的异步函数的结果。
  • refresh/execute:一个可用于刷新 handler 函数返回数据的函数。
  • error:如果数据获取失败,则返回一个错误对象。
  • status:一个指示数据请求状态的字符串:
    • idle:请求尚未开始,例如:
      • execute 尚未调用且设置了 { immediate: false }
      • 当在服务器端渲染 HTML 且设置了 { server: false }
    • pending:请求正在进行。
    • success:请求已成功完成。
    • error:请求已失败。
  • clear:一个函数,将 data 设置为 undefined,将 error 设置为 null,将 status 设置为 'idle',并将任何当前待处理的请求标记为已取消。

默认情况下,Nuxt 会等待 refresh 完成后再再次执行。

如果您未在服务器端获取数据(例如,设置了 server: false),那么在水合完成前不会获取数据。这意味着即使您在客户端 await useFetch,在 <script setup>data 仍将保持为 null

类型

Signature
function useFetch<DataT, ErrorT>(
  url: string | Request | Ref<string | Request> | (() => string | Request),
  options?: UseFetchOptions<DataT>
): Promise<AsyncData<DataT, ErrorT>>

type UseFetchOptions<DataT> = {
  key?: string
  method?: string
  query?: SearchParams
  params?: SearchParams
  body?: RequestInit['body'] | Record<string, any>
  headers?: Record<string, string> | [key: string, value: string][] | Headers
  baseURL?: string
  server?: boolean
  lazy?: boolean
  immediate?: boolean
  getCachedData?: (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined
  deep?: boolean
  dedupe?: 'cancel' | 'defer'
  default?: () => DataT
  transform?: (input: DataT) => DataT | Promise<DataT>
  pick?: string[]
  watch?: WatchSource[] | false
}

type AsyncDataRequestContext = {
  /** The reason for this data request */
  cause: 'initial' | 'refresh:manual' | 'refresh:hook' | 'watch'
}

type AsyncData<DataT, ErrorT> = {
  data: Ref<DataT | null>
  refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
  execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
  clear: () => void
  error: Ref<ErrorT | null>
  status: Ref<AsyncDataRequestStatus>
}

interface AsyncDataExecuteOptions {
  dedupe?: 'cancel' | 'defer'
}

type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'