译零 TransZero · TanStack Query 中文文档
主站

预取

更新于 2026-11-02 Vue 查看英文原文 ↗

如果你足够幸运,能提前预判用户接下来的操作,就可以在用户真正需要数据之前预先拉取所需数据。若符合此场景,请使用 queryClient.query 或 queryClient.infiniteQuery 提前填充缓存:

TypeScript
1import { noop } from '@tanstack/vue-query'2 3const prefetchTodos = async () => {4  // The results of this query will be cached like a normal query5  await queryClient6    .query({7      queryKey: ['todos'],8      queryFn: fetchTodos,9    })10    .catch(noop)11}
  • 若该查询的新鲜数据已存在于缓存中,则不会发起拉取;
  • 若传入了 staleTime(例如 queryClient.query({ queryKey: ['todos'], queryFn: fn, staleTime: 5 * 1000 })),且缓存中的数据已超过指定 staleTime 时长,则会发起查询拉取;
  • 由于 useQuery 会自动重试拉取并处理错误,你可以使用 void 忽略 query 返回的 Promise,或使用 .catch(noop) 忽略错误;
  • 若你希望只要缓存中存在数据就始终返回缓存数据,请使用 staleTime: 'static';
  • 若一个已预取的查询后续未被任何 useQuery 实例引用,它将在 gcTime 指定的时间后被删除并进入垃圾回收。

预取无限查询

无限查询(infinite queries)可像普通查询一样进行预取。默认情况下,仅预取查询的第一页,并将其存储在给定的查询键(QueryKey)下。若需预取多页,可使用 pages 选项;此时你还必须提供一个 getNextPageParam 函数:

TypeScript
1import { noop } from '@tanstack/vue-query'2 3const prefetchProjects = async () => {4  // The results of this query will be cached like a normal query5  await queryClient6    .infiniteQuery({7      queryKey: ['projects'],8      queryFn: fetchProjects,9      initialPageParam: 0,10      getNextPageParam: (lastPage, pages) => lastPage.nextCursor,11      pages: 3, // prefetch the first 3 pages12    })13    .catch(noop)14}

上述代码将按顺序尝试预取 3 页,且每页都会执行 getNextPageParam 以确定下一页的预取参数。若 getNextPageParam 返回 undefined,则预取过程将停止。

本页为 TanStack Query 文档(Vue 版)的非官方中文翻译,原文由上游团队维护,遵循 MIT 许可。 译文如有偏差,以英文原文为准。

译自上游 59d11de