useAsyncData
在你的页面、组件和插件中,你可以使用 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
<script setup lang="ts">
const { data, status, error, refresh, clear } = await useAsyncData(
'mountains',
() => $fetch('https://api.nuxtjs.dev/mountains')
)
</script>
data
、status
和 error
是 Vue 引用,在 <script setup>
中使用时应通过 .value
访问,而 refresh
/execute
和 clear
是普通函数。观看参数
¥Watch Params
内置的 watch
选项允许在检测到任何更改时自动重新运行抓取器功能。
¥The built-in watch
option allows automatically rerunning the fetcher function when any changes are detected.
<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:
<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
.参数
¥Params
key
:一个唯一键,用于确保数据提取能够在请求之间正确去重。如果你未提供密钥,那么系统将为你生成一个与useAsyncData
实例的文件名和行号唯一的密钥。handler
:一个异步函数,必须返回真值(例如,它不应该是undefined
或null
),否则请求可能会在客户端重复。
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: true
或immediate: false
选项配合使用非常有用transform
:一个函数,用于在解析后更改handler
函数的结果getCachedData
:提供一个返回缓存数据的函数。null
或undefined
的返回值将触发抓取。默认情况下:const getDefaultCachedData = (key, nuxtApp, ctx) => nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key]
仅在启用nuxt.config
的experimental.payloadExtraction
时缓存数据。pick
:仅从handler
函数结果中选取此数组中的指定键。watch
:监视响应式源以自动刷新deep
:在深度引用对象中返回数据。默认情况下,false
会将数据返回到浅引用对象中以提高性能。dedupe
:避免一次多次获取相同的键(默认为cancel
)。可能的选项:cancel
- 发出新请求时取消现有请求defer
- 如果有待处理的请求,则根本不发出新请求。
lazy: false
使用 <Suspense>
在数据获取之前阻止路由加载。为了获得更流畅的用户体验,请考虑使用 lazy: true
并实现加载状态。:
你可以使用 useLazyAsyncData
和 useAsyncData
实现与 lazy: true
相同的行为。
¥You can use useLazyAsyncData
to have the same behavior as lazy: true
with useAsyncData
.
::
共享状态和选项一致性
¥Shared State and Option Consistency
当对多个 useAsyncData
调用使用相同的键时,它们将共享相同的 data
、error
和 status
引用。这确保了跨组件的一致性,但需要选项的一致性。
¥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 完成之前,数据将不会被获取。这意味着,即使你在客户端等待 useAsyncData
,data
在 <script setup>
中仍将保持为 null
。类型
¥Type
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'