useAsyncData

useAsyncData 提供对服务器端渲染 (SSR) 友好型可组合项中异步解析的数据的访问。

在你的页面、组件和插件中,你可以使用 useAsyncData 来访问异步解析的数据。

¥Within your pages, components, and plugins you can use useAsyncData to get access to data that resolves asynchronously.

useAsyncData 是一个可组合函数,旨在直接在 Nuxt context 中调用。它返回响应式可组合项,并处理向 Nuxt 有效负载添加响应,以便在页面合并时将它们从服务器传递到客户端 without re-fetching the data on client side

用法

¥Usage

pages/index.vue
<script setup lang="ts">
const { data, status, error, refresh, clear } = await useAsyncData(
  'mountains',
  () => $fetch('https://api.nuxtjs.dev/mountains')
)
</script>
如果你正在使用自定义 useAsyncData 封装器,请勿在可组合项中等待它,因为这可能会导致意外行为。请关注 此方法 以获取有关如何创建自定义异步数据获取器的更多信息。¥If you're using a custom useAsyncData 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 是普通函数。

观看参数

¥Watch Params

内置的 watch 选项允许在检测到任何更改时自动重新运行抓取器功能。

¥The built-in watch option allows automatically rerunning the fetcher function when any changes are detected.

pages/index.vue
<script setup lang="ts">
const page = ref(1)
const { data: posts } = await useAsyncData(
  'posts',
  () => $fetch('https://fakeApi.com/posts', {
    params: {
      page: page.value
    }
  }), {
    watch: [page]
  }
)
</script>

响应式键

¥Reactive Keys

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

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

pages/[id].vue
<script setup lang="ts">
const route = useRoute()
const userId = computed(() => `user-${route.params.id}`)

// When the route changes and userId updates, the data will be automatically refetched
const { data: user } = useAsyncData(
  userId,
  () => fetchUserById(route.params.id)
)
</script>
useAsyncData 是一个由编译器转换的保留函数名,因此你不应将自己的函数命名为 useAsyncData。¥useAsyncData is a reserved function name transformed by the compiler, so you should not name your own function useAsyncData.
Read more in Docs > Getting Started > Data Fetching#useasyncdata.

参数

¥Params

  • key:一个唯一键,用于确保数据提取能够在请求之间正确去重。如果你未提供密钥,那么系统将为你生成一个与 useAsyncData 实例的文件名和行号唯一的密钥。
  • handler:一个异步函数,必须返回真值(例如,它不应该是 undefinednull),否则请求可能会在客户端重复。
handler 函数应该没有副作用,以确保在 SSR 和 CSR 混合期间的行为可预测。如果你需要触发副作用,请使用 callOnce 实用程序来实现。¥The handler function should be side-effect free to ensure predictable behavior during SSR and CSR hydration. If you need to trigger side effects, use the callOnce utility to do so.
  • options
    • 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:监视响应式源以自动刷新
    • deep:在深度引用对象中返回数据。默认情况下,false 会将数据返回到浅引用对象中以提高性能。
    • dedupe:避免一次多次获取相同的键(默认为 cancel)。可能的选项:
      • cancel - 发出新请求时取消现有请求
      • defer - 如果有待处理的请求,则根本不发出新请求。
在底层,lazy: false 使用 <Suspense> 在数据获取之前阻止路由加载。为了获得更流畅的用户体验,请考虑使用 lazy: true 并实现加载状态。

:

Read more in Docs > API > Composables > Use Lazy Async Data.

你可以使用 useLazyAsyncDatauseAsyncData 实现与 lazy: true 相同的行为。

¥You can use useLazyAsyncData to have the same behavior as lazy: true with useAsyncData.

::

共享状态和选项一致性

¥Shared State and Option Consistency

当对多个 useAsyncData 调用使用相同的键时,它们将共享相同的 dataerrorstatus 引用。这确保了跨组件的一致性,但需要选项的一致性。

¥When using the same key for multiple useAsyncData calls, they will share the same data, error and status refs. This ensures consistency across components but requires option consistency.

以下选项在使用相同键的所有调用中必须保持一致:

¥The following options must be consistent across all calls with the same key:

  • handler 函数
  • deep 选项
  • transform 函数
  • pick 数组
  • getCachedData 函数
  • default

以下选项可以不同而不会触发警告:

¥The following options can differ without triggering warnings:

  • server
  • lazy
  • immediate
  • dedupe
  • watch
// ❌ This will trigger a development warning
const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { deep: false })
const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { deep: true })

// ✅ This is allowed
const { data: users1 } = useAsyncData('users', () => $fetch('/api/users'), { immediate: true })
const { data: users2 } = useAsyncData('users', () => $fetch('/api/users'), { immediate: false })

返回值

¥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 完成之前,数据将不会被获取。这意味着,即使你在客户端等待 useAsyncDatadata<script setup> 中仍将保持为 null

类型

¥Type

Signature
function useAsyncData<DataT, DataE>(
  handler: (nuxtApp?: NuxtApp) => Promise<DataT>,
  options?: AsyncDataOptions<DataT>
): AsyncData<DataT, DataE>
function useAsyncData<DataT, DataE>(
  key: string | Ref<string> | ComputedRef<string>,
  handler: (nuxtApp?: NuxtApp) => Promise<DataT>,
  options?: AsyncDataOptions<DataT>
): Promise<AsyncData<DataT, DataE>>

type AsyncDataOptions<DataT> = {
  server?: boolean
  lazy?: boolean
  immediate?: boolean
  deep?: boolean
  dedupe?: 'cancel' | 'defer'
  default?: () => DataT | Ref<DataT> | null
  transform?: (input: DataT) => DataT | Promise<DataT>
  pick?: string[]
  watch?: WatchSource[] | false
  getCachedData?: (key: string, nuxtApp: NuxtApp, ctx: AsyncDataRequestContext) => DataT | undefined
}

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'
Read more in Docs > Getting Started > Data Fetching.