tanstack-vue-query-skilld

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack/query
@tanstack/vue-query

TanStack/query
@tanstack/vue-query

Version: 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:
    useQuery
    signature — v5 requires a single object argument
    { queryKey, queryFn, ... }
    . Old positional arguments are no longer supported and will result in errors source
  • BREAKING:
    useQueries
    signature — v5 now takes an object with a
    queries
    array property:
    useQueries({ queries: [...] })
    . This allows for additional top-level options like
    combine
  • BREAKING:
    useQueries
    return type — now returns a
    Ref
    of the results array instead of a
    reactive
    array, ensuring better compatibility with Vue 2 and avoiding spread reactivity loss source
  • BREAKING: Callback removal —
    onSuccess
    ,
    onError
    , and
    onSettled
    are removed from
    useQuery
    ,
    useInfiniteQuery
    , and
    useQueries
    . Use
    select
    for data transformation or global
    QueryCache
    callbacks instead source
  • BREAKING:
    cacheTime
    renamed — renamed to
    gcTime
    (Garbage Collection time) across all options and default options to better reflect its purpose source
  • BREAKING:
    useInfiniteQuery
    parameters —
    getNextPageParam
    and
    getPreviousPageParam
    now receive a single object containing
    lastPage
    ,
    allPages
    ,
    lastPageParam
    , and
    allPageParams
    source
  • BREAKING:
    keepPreviousData
    removed — the option is replaced by the
    placeholderData: keepPreviousData
    helper function from
    @tanstack/vue-query
    source
  • NEW:
    queryOptions
    /
    infiniteQueryOptions
    — helper functions for sharing query definitions with type safety across components and for prefetching source
  • NEW:
    useMutationState
    — new composable to access mutation state globally by filtering for specific mutations based on keys or filters
  • NEW: Options Getter support —
    useQuery
    and
    useInfiniteQuery
    now support passing a getter function (e.g.,
    () => options
    ) or a
    Ref
    for the entire options object, enabling easier reactivity
  • NEW:
    combine
    for
    useQueries
    — allows merging multiple query results into a single value (e.g., a single object or a derived state) via the
    combine
    option
  • NEW: Injection Context —
    vue-query
    composables can now be used in any function that supports
    injectionContext
    (e.g., router guards) if used within an
    effectScope
    source
  • DEPRECATED:
    isLoading
    — renamed to
    isPending
    in v5. The
    isLoading
    property now specifically means
    isPending && isFetching
    (fetching for the first time) source
  • BREAKING: Vue 3.3 requirement — minimum Vue version for
    @tanstack/vue-query
    v5 is now 3.3 to support newer reactivity features source
Also changed:
isPlaceholderData
boolean result new v5 ·
initialPageParam
required for
useInfiniteQuery
·
isPaused
property added to query results ·
Suspense
(experimental) supported via
suspense()
method (experimental)
本节记录特定版本的API变更 — 优先关注近期的大版本/小版本发布。
  • 破坏性变更:
    useQuery
    签名 — v5要求传入单个对象参数
    { queryKey, queryFn, ... }
    。旧的位置参数不再被支持,使用会导致错误 来源
  • 破坏性变更:
    useQueries
    签名 — v5现在接收一个包含
    queries
    数组属性的对象:
    useQueries({ queries: [...] })
    。这允许添加
    combine
    等额外的顶层选项
  • 破坏性变更:
    useQueries
    返回类型 — 现在返回结果数组的
    Ref
    对象,而非
    reactive
    数组,确保与Vue 2更好的兼容性,避免展开时丢失响应式 来源
  • 破坏性变更:移除回调函数 —
    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
    useInfiniteQuery
    现在支持传入Getter函数(如
    () => options
    )或整个选项对象的
    Ref
    ,使响应式实现更简单
  • 新增功能:
    useQueries
    combine
    选项 — 允许通过
    combine
    选项将多个查询结果合并为单个值(例如单个对象或派生状态)
  • 新增功能:注入上下文 —
    vue-query
    组合式函数现在可在任何支持
    injectionContext
    的函数中使用(如路由守卫),前提是在
    effectScope
    内调用 来源
  • 废弃:
    isLoading
    — 在v5中更名为
    isPending
    isLoading
    属性现在特指
    isPending && isFetching
    (首次获取数据时的加载状态) 来源
  • 破坏性变更:要求Vue 3.3 —
    @tanstack/vue-query
    v5的最低Vue版本为3.3,以支持更新的响应式特性 来源
其他变更: v5新增
isPlaceholderData
布尔结果 ·
useInfiniteQuery
需要
initialPageParam
· 查询结果新增
isPaused
属性 · 支持
Suspense
(实验性),通过
suspense()
方法启用(实验性)

Best Practices

最佳实践

  • Use
    MaybeRefOrGetter
    for composable parameters to support refs, plain values, and reactive getters seamlessly source
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
    computed
    for simple property access to avoid unnecessary memoization overhead source
ts
// Preferred: No computed needed
const { data } = useUserProjects(() => props.userId)

// Avoid: Unnecessary memoization
const userId = computed(() => props.userId)
const { data } = useUserProjects(userId)
  • Use
    onServerPrefetch
    with the
    suspense()
    helper to ensure queries are awaited during SSR source
ts
const { data, suspense } = useQuery({ queryKey: ['test'], queryFn: fetcher })
onServerPrefetch(suspense)
  • Set
    staleTime
    to a value greater than 0 for SSR to prevent immediate background refetching on the client source
ts
const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 1000 * 60 * 5 } }
})
  • Manually call
    queryClient.clear()
    after request handling if
    gcTime
    is set to a non-Infinity value on the server to prevent memory leaks source
  • Treat
    useQuery
    results as immutable and clone data before using it with two-way bindings like
    v-model
    source
ts
const { data } = useQuery({ ... })
const model = ref()
watch(data, (newData) => {
  model.value = JSON.parse(JSON.stringify(newData))
}, { immediate: true })
  • Use the
    queryOptions
    helper to define type-safe, reusable query configurations that can be shared across components
ts
const userOptions = (id: string) => queryOptions({
  queryKey: ['user', id],
  queryFn: () => fetchUser(id)
})

useQuery(userOptions('123'))
  • Include all reactive dependencies in the
    queryKey
    to ensure Vue Query tracks them and refetches automatically on change source
  • Utilize a custom
    queryClientKey
    when running multiple Vue applications on the same page to prevent QueryClient instance clashing source
ts
// Plugin configuration
app.use(VueQueryPlugin, { queryClientKey: 'AppA' })

// Usage
useQuery({ queryKey: ['data'], queryFn: fetcher, queryClientKey: 'AppA' })
  • 使用
    MaybeRefOrGetter
    作为组合式函数的参数,以无缝支持ref、普通值和响应式getter 来源
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
    suspense()
    辅助函数,确保SSR期间查询被等待完成 来源
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 } }
})
  • 如果服务器上
    gcTime
    设置为非Infinity值,请求处理完成后手动调用
    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'))
  • 将所有响应式依赖项包含在
    queryKey
    中,确保Vue Query能够跟踪它们,并在变更时自动重新获取数据 来源
  • 当同一页面运行多个Vue应用时,使用自定义
    queryClientKey
    以避免QueryClient实例冲突 来源
ts
// 插件配置
app.use(VueQueryPlugin, { queryClientKey: 'AppA' })

// 使用方式
useQuery({ queryKey: ['data'], queryFn: fetcher, queryClientKey: 'AppA' })