useFetch

使用支持服务器端渲染 (SSR) 的可组合组件从 API 端点获取数据。

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

¥This composable provides a convenient wrapper around useAsyncData and $fetch. It automatically generates a key based on URL and fetch options, provides type hints for request url based on server routes, and infers API response type.

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

用法

¥Usage

pages/modules.vue
<script setup lang="ts">
const { data, status, error, refresh, clear } = await useFetch('/api/modules', {
  pick: ['title']
})
</script>
如果你使用自定义 useFetch 封装器,请勿在可组合项中等待它,因为这可能会导致意外行为。请关注 此方法 以获取有关如何创建自定义异步数据获取器的更多信息。¥If you're using a custom useFetch wrapper, do not await it in the composable, as that can cause unexpected behavior. Please follow this recipe for more information on how to make a custom async data fetcher.
datastatuserror 是 Vue 引用,在 <script setup> 中使用时,应通过 .value 访问,而 refresh/executeclear 是普通函数。

使用 query 选项,你可以将搜索参数添加到查询中。此选项扩展自 unjs/ofetch,并使用 unjs/ufo 创建 URL。对象会自动字符串化。

¥Using the query option, you can add search parameters to your query. This option is extended from unjs/ofetch and is using unjs/ufo to create the URL. Objects are automatically stringified.

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

上述示例生成了 https://api.nuxt.com/modules?param1=value1&param2=value2

¥The above example results in https://api.nuxt.com/modules?param1=value1&param2=value2.

你还可以使用 interceptors

¥You can also use interceptors:

const { data, status, error, refresh, clear } = await useFetch('/api/auth/login', {
  onRequest({ request, options }) {
    // Set the request headers
    // note that this relies on ofetch >= 1.4.0 - you may need to refresh your lockfile
    options.headers.set('Authorization', '...')
  },
  onRequestError({ request, options, error }) {
    // Handle the request errors
  },
  onResponse({ request, response, options }) {
    // Process the response data
    localStorage.setItem('token', response._data.token)
  },
  onResponseError({ request, response, options }) {
    // Handle the response errors
  }
})

响应式键和共享状态

¥Reactive Keys and Shared State

你可以使用计算引用或纯文本引用作为 URL,从而允许动态数据获取,并在 URL 更改时自动更新:

¥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>

在多个组件中使用具有相同 URL 和选项的 useFetch 时,它们将共享相同的 dataerrorstatus 引用。这确保了组件间的一致性。

¥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 is a reserved function name transformed by the compiler, so you should not name your own function useFetch.
如果你遇到从 useFetch 解构的 data 变量返回字符串而不是 JSON 解析对象,请确保你的组件不包含像 import { useFetch } from '@vueuse/core 这样的导入语句。¥If you encounter the data variable destructured from a useFetch returns a string and not a JSON parsed object then make sure your component doesn't include an import statement like import { useFetch } from '@vueuse/core.

Read more in Docs > Getting Started > Data Fetching.
Read and edit a live example in Docs > Examples > Features > Data Fetching.

参数

¥Params

  • URL:要获取的 URL。
  • Options(扩展 unjs/ofetch 选项和 AsyncDataOptions):
    • method:请求方法。
    • query:使用 ufo 将查询搜索参数添加到 URL
    • paramsquery 的别名
    • body:请求正文 - 自动字符串化(如果传递了对象)。
    • headers:请求标头。
    • baseURL:请求的基本 URL。
    • timeout:自动中止请求的毫秒数
    • cache:根据 获取 API 处理缓存控制。
      • 你可以传递布尔值来禁用缓存,或者传递以下值之一:defaultno-storereloadno-cacheforce-cacheonly-if-cached
所有获取选项都可以指定 computedref 值。这些值将被监视,并且如果更新,将自动使用任何新值发出新请求。
  • Options(来自 useAsyncData):
    • key:一个唯一键,用于确保数据提取能够在请求之间正确去重。如果未提供,则会根据 URL 和提取选项自动生成。
    • 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:监视响应式源数组,并在它们发生变化时自动刷新获取结果。默认情况下,获取选项和 URL 会被监视。你可以使用 watch: false 完全忽略响应式源。与 immediate: false 结合使用,可实现完全手动的 useFetch。(你可以选择 查看此处的示例 或使用 watch。)
    • deep:在深度引用对象中返回数据。默认情况下,false 会将数据返回到浅引用对象中以提高性能。
    • dedupe:避免一次多次获取相同的键(默认为 cancel)。可能的选项:
      • cancel - 发出新请求时取消现有请求
      • defer - 如果有待处理的请求,则根本不发出新请求。
如果你提供函数或引用作为 url 参数,或者如果你提供函数作为 options 参数的实参,那么 useFetch 调用将不会匹配代码库中其他位置的 useFetch 调用,即使选项看起来相同。如果你希望强制匹配,你可以在 options 中提供自己的密钥。
如果你在开发环境中使用 useFetch 调用带有自签名证书的(外部)HTTPS URL,则需要在你的环境中设置 NODE_TLS_REJECT_UNAUTHORIZED=0

返回值

¥Return Values

  • 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 完成后才能再次执行。

¥By default, Nuxt waits until a refresh is finished before it can be executed again.

如果你尚未在服务器上获取数据(例如,使用 server: false),则在 hydration 完成之前,数据将不会被获取。这意味着,即使你在客户端等待 useFetchdata<script setup> 中仍将保持为 null。

类型

¥Type

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'