tanstack-vue-query-skilld
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTanStack/query @tanstack/vue-query
@tanstack/vue-queryTanStack/query @tanstack/vue-query
@tanstack/vue-queryVersion: 5.92.9 (Jan 2026)
Deps: @tanstack/match-sorter-utils@^8.19.4, @vue/devtools-api@^6.6.3, vue-demi@^0.14.10, @tanstack/query-core@5.90.20
Tags: alpha: 5.0.0-alpha.91 (Jul 2023), beta: 5.0.0-beta.35 (Sep 2023), rc: 5.0.0-rc.16 (Oct 2023), latest: 5.92.9 (Jan 2026), previous: 4.43.0 (Jan 2026)
References: Docs — API reference, guides • GitHub Issues — bugs, workarounds, edge cases • GitHub Discussions — Q&A, patterns, recipes • Releases — changelog, breaking changes, new APIs
版本: 5.92.9(2026年1月)
依赖项: @tanstack/match-sorter-utils@^8.19.4、@vue/devtools-api@^6.6.3、vue-demi@^0.14.10、@tanstack/query-core@5.90.20
版本标签: alpha: 5.0.0-alpha.91(2023年7月)、beta: 5.0.0-beta.35(2023年9月)、rc: 5.0.0-rc.16(2023年10月)、latest: 5.92.9(2026年1月)、previous: 4.43.0(2026年1月)
参考链接: 文档 — API参考、指南 • GitHub Issues — 问题、解决方案、边缘案例 • GitHub Discussions — 问答、模式、实践方案 • 版本发布记录 — 更新日志、破坏性变更、新API
API Changes
API变更
This section documents version-specific API changes — prioritize recent major/minor releases.
-
BREAKING:signature — v5 requires a single object argument
useQuery. Old positional arguments are no longer supported and will result in errors source{ queryKey, queryFn, ... } -
BREAKING:signature — v5 now takes an object with a
useQueriesarray property:queries. This allows for additional top-level options likeuseQueries({ queries: [...] })combine -
BREAKING:return type — now returns a
useQueriesof the results array instead of aRefarray, ensuring better compatibility with Vue 2 and avoiding spread reactivity loss sourcereactive -
BREAKING: Callback removal —,
onSuccess, andonErrorare removed fromonSettled,useQuery, anduseInfiniteQuery. UseuseQueriesfor data transformation or globalselectcallbacks instead sourceQueryCache -
BREAKING:renamed — renamed to
cacheTime(Garbage Collection time) across all options and default options to better reflect its purpose sourcegcTime -
BREAKING:parameters —
useInfiniteQueryandgetNextPageParamnow receive a single object containinggetPreviousPageParam,lastPage,allPages, andlastPageParamsourceallPageParams -
BREAKING:removed — the option is replaced by the
keepPreviousDatahelper function fromplaceholderData: keepPreviousDatasource@tanstack/vue-query -
NEW:/
queryOptions— helper functions for sharing query definitions with type safety across components and for prefetching sourceinfiniteQueryOptions -
NEW:— new composable to access mutation state globally by filtering for specific mutations based on keys or filters
useMutationState -
NEW: Options Getter support —and
useQuerynow support passing a getter function (e.g.,useInfiniteQuery) or a() => optionsfor the entire options object, enabling easier reactivityRef -
NEW:for
combine— allows merging multiple query results into a single value (e.g., a single object or a derived state) via theuseQueriesoptioncombine -
NEW: Injection Context —composables can now be used in any function that supports
vue-query(e.g., router guards) if used within aninjectionContextsourceeffectScope -
DEPRECATED:— renamed to
isLoadingin v5. TheisPendingproperty now specifically meansisLoading(fetching for the first time) sourceisPending && isFetching -
BREAKING: Vue 3.3 requirement — minimum Vue version forv5 is now 3.3 to support newer reactivity features source
@tanstack/vue-query
Also changed: boolean result new v5 · required for · property added to query results · (experimental) supported via method (experimental)
isPlaceholderDatainitialPageParamuseInfiniteQueryisPausedSuspensesuspense()本节记录特定版本的API变更 — 优先关注近期的大版本/小版本发布。
-
破坏性变更:签名 — v5要求传入单个对象参数
useQuery。旧的位置参数不再被支持,使用会导致错误 来源{ queryKey, queryFn, ... } -
破坏性变更:签名 — v5现在接收一个包含
useQueries数组属性的对象:queries。这允许添加useQueries({ queries: [...] })等额外的顶层选项combine -
破坏性变更:返回类型 — 现在返回结果数组的
useQueries对象,而非Ref数组,确保与Vue 2更好的兼容性,避免展开时丢失响应式 来源reactive -
破坏性变更:移除回调函数 —、
onSuccess和onError从onSettled、useQuery和useInfiniteQuery中移除。请使用useQueries进行数据转换,或改用全局select回调函数 来源QueryCache -
破坏性变更:重命名 — 在所有选项和默认选项中更名为
cacheTime(垃圾回收时间),以更准确地反映其用途 来源gcTime -
破坏性变更:参数 —
useInfiniteQuery和getNextPageParam现在接收一个包含getPreviousPageParam、lastPage、allPages和lastPageParam的单个对象 来源allPageParams -
破坏性变更:移除— 该选项被
keepPreviousData中的@tanstack/vue-query辅助函数取代 来源placeholderData: keepPreviousData -
新增功能:/
queryOptions— 辅助函数,用于跨组件以类型安全的方式共享查询定义,以及用于预取数据 来源infiniteQueryOptions -
新增功能:— 新的组合式函数,可通过按键或过滤器筛选特定突变,全局访问突变状态
useMutationState -
新增功能:支持选项Getter —和
useQuery现在支持传入Getter函数(如useInfiniteQuery)或整个选项对象的() => options,使响应式实现更简单Ref -
新增功能:的
useQueries选项 — 允许通过combine选项将多个查询结果合并为单个值(例如单个对象或派生状态)combine -
新增功能:注入上下文 —组合式函数现在可在任何支持
vue-query的函数中使用(如路由守卫),前提是在injectionContext内调用 来源effectScope -
废弃:— 在v5中更名为
isLoading。isPending属性现在特指isLoading(首次获取数据时的加载状态) 来源isPending && isFetching -
破坏性变更:要求Vue 3.3 —v5的最低Vue版本为3.3,以支持更新的响应式特性 来源
@tanstack/vue-query
其他变更: v5新增布尔结果 · 需要 · 查询结果新增属性 · 支持(实验性),通过方法启用(实验性)
isPlaceholderDatauseInfiniteQueryinitialPageParamisPausedSuspensesuspense()Best Practices
最佳实践
- Use for composable parameters to support refs, plain values, and reactive getters seamlessly source
MaybeRefOrGetter
ts
// Preferred: Accepts ref, getter, or value
export function useUser(id: MaybeRefOrGetter<string>) {
return useQuery({
queryKey: ['user', id],
queryFn: () => fetchUser(toValue(id))
})
}- Pass the entire options object as a getter function to reactively update multiple query parameters at once (v5.91.0+) source
ts
// Preferred for complex reactivity
useQuery(() => ({
queryKey: ['todo', id.value],
queryFn: () => fetchTodo(id.value),
enabled: !!id.value
}))- Prefer reactive getters over for simple property access to avoid unnecessary memoization overhead source
computed
ts
// Preferred: No computed needed
const { data } = useUserProjects(() => props.userId)
// Avoid: Unnecessary memoization
const userId = computed(() => props.userId)
const { data } = useUserProjects(userId)- Use with the
onServerPrefetchhelper to ensure queries are awaited during SSR sourcesuspense()
ts
const { data, suspense } = useQuery({ queryKey: ['test'], queryFn: fetcher })
onServerPrefetch(suspense)- Set to a value greater than 0 for SSR to prevent immediate background refetching on the client source
staleTime
ts
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 1000 * 60 * 5 } }
})-
Manually callafter request handling if
queryClient.clear()is set to a non-Infinity value on the server to prevent memory leaks sourcegcTime -
Treatresults as immutable and clone data before using it with two-way bindings like
useQuerysourcev-model
ts
const { data } = useQuery({ ... })
const model = ref()
watch(data, (newData) => {
model.value = JSON.parse(JSON.stringify(newData))
}, { immediate: true })- Use the helper to define type-safe, reusable query configurations that can be shared across components
queryOptions
ts
const userOptions = (id: string) => queryOptions({
queryKey: ['user', id],
queryFn: () => fetchUser(id)
})
useQuery(userOptions('123'))-
Include all reactive dependencies in theto ensure Vue Query tracks them and refetches automatically on change source
queryKey -
Utilize a customwhen running multiple Vue applications on the same page to prevent QueryClient instance clashing source
queryClientKey
ts
// Plugin configuration
app.use(VueQueryPlugin, { queryClientKey: 'AppA' })
// Usage
useQuery({ queryKey: ['data'], queryFn: fetcher, queryClientKey: 'AppA' })- 使用作为组合式函数的参数,以无缝支持ref、普通值和响应式getter 来源
MaybeRefOrGetter
ts
// 推荐写法:支持ref、getter或普通值
export function useUser(id: MaybeRefOrGetter<string>) {
return useQuery({
queryKey: ['user', id],
queryFn: () => fetchUser(toValue(id))
})
}- 将整个选项对象作为Getter函数传入,以响应式地同时更新多个查询参数(v5.91.0+) 来源
ts
// 复杂响应式场景推荐写法
useQuery(() => ({
queryKey: ['todo', id.value],
queryFn: () => fetchTodo(id.value),
enabled: !!id.value
}))- 对于简单属性访问,优先使用响应式getter而非,避免不必要的记忆化开销 来源
computed
ts
// 推荐写法:无需computed
const { data } = useUserProjects(() => props.userId)
// 不推荐:不必要的记忆化
const userId = computed(() => props.userId)
const { data } = useUserProjects(userId)- 结合和
onServerPrefetch辅助函数,确保SSR期间查询被等待完成 来源suspense()
ts
const { data, suspense } = useQuery({ queryKey: ['test'], queryFn: fetcher })
onServerPrefetch(suspense)- 为SSR设置大于0的,防止客户端加载后立即进行后台重新获取 来源
staleTime
ts
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: 1000 * 60 * 5 } }
})-
如果服务器上设置为非Infinity值,请求处理完成后手动调用
gcTime以防止内存泄漏 来源queryClient.clear() -
将结果视为不可变数据,在与
useQuery等双向绑定一起使用前克隆数据 来源v-model
ts
const { data } = useQuery({ ... })
const model = ref()
watch(data, (newData) => {
model.value = JSON.parse(JSON.stringify(newData))
}, { immediate: true })- 使用辅助函数定义类型安全、可复用的查询配置,以便在组件间共享
queryOptions
ts
const userOptions = (id: string) => queryOptions({
queryKey: ['user', id],
queryFn: () => fetchUser(id)
})
useQuery(userOptions('123'))-
将所有响应式依赖项包含在中,确保Vue Query能够跟踪它们,并在变更时自动重新获取数据 来源
queryKey -
当同一页面运行多个Vue应用时,使用自定义以避免QueryClient实例冲突 来源
queryClientKey
ts
// 插件配置
app.use(VueQueryPlugin, { queryClientKey: 'AppA' })
// 使用方式
useQuery({ queryKey: ['data'], queryFn: fetcher, queryClientKey: 'AppA' })