How to Supercharge Axios in Vue 3 with TanStack Query
This article explains how TanStack Query Vue transforms the plain Axios HTTP client into a full‑featured data layer for Vue 3, offering built‑in caching, pagination, request cancellation, optimistic updates, and devtools, with concrete code examples and side‑by‑side comparisons to pure Axios usage.
What is TanStack Query Vue
TanStack Query Vue (npm package @tanstack/vue-query) is the Vue sibling of React Query. It is positioned as a “data‑layer operating system” rather than a simple HTTP client, providing a second‑level wrapper for any function that returns a Promise (e.g., Axios, fetch, GraphQL SDK).
Key Features
Automatic cache / invalidation / garbage collection (built‑in LRU).
One‑line pagination, infinite scroll, and dependent queries via useInfiniteQuery and enabled.
Request cancellation with cancel() or automatic AbortSignal.
Conditional (dependent) queries using the enabled flag.
Parallel or sequential request orchestration.
Optimistic updates via onMutate with automatic rollback.
Official Devtools panel for inspecting cache keys, data, and expiration.
Advantages Over Pure Axios
Data caching: TanStack Query Vue provides built‑in LRU cache and auto‑gc, whereas with pure Axios you would need to implement a Map yourself.
Pagination / infinite loading: One‑line useInfiniteQuery replaces manual page number handling and array concatenation.
Request cancellation: One‑click cancel() or automatic AbortSignal vs. manually creating an AbortController.
Dependent queries: Use the enabled flag instead of writing a watch on a variable.
Parallel / serial execution: TanStack Query handles concurrent or dependent dispatches, while pure Axios requires manual Promise.all or chained then calls.
Optimistic updates: onMutate with rollback vs. hand‑written snapshot logic.
Debugging: Official Devtools panel vs. console logging.
Quick Start (3 minutes)
Install the package: npm i @tanstack/vue-query Register the plugin in main.ts:
import { VueQueryPlugin } from '@tanstack/vue-query'
createApp(App).use(VueQueryPlugin).mount('#app')Use useQuery inside a component:
<script setup>
import { useQuery } from '@tanstack/vue-query'
const { data, isLoading, isError } = useQuery({
queryKey: ['posts'],
queryFn: () => axios.post('/api/posts').then(r => r.json())
})
</script>
<template>
<div v-if="isLoading">加载中...</div>
<div v-else-if="isError">请求失败</div>
<ul v-else>
<li v-for="p in data" :key="p.id">{{ p.title }}</li>
</ul>
</template>Four Common Real‑World Scenarios
1. Conditional (dependent) query
const { data } = useQuery({
queryKey: ['user', userId],
queryFn: () => axios.get(`/api/user/${userId.value}`).then(r => r.json()),
enabled: !!userId.value // only fire when userId exists
})2. Infinite scroll
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
queryKey: ['comments'],
queryFn: ({ pageParam = 1 }) =>
axios.get(`/api/comments?page=${pageParam}`).then(r => r.json()),
getNextPageParam: last => last.nextPage ?? false
})3. Parallel multiple requests
const ids = [1, 2, 3]
const queries = ids.map(id =>
useQuery({
queryKey: ['item', id],
queryFn: () => axios.get(`/api/item/${id}`).then(r => r.json())
})
)
// queries[i].data holds the result for each id4. Form submission with optimistic update
const queryClient = useQueryClient()
const { mutate } = useMutation({
mutationFn: newTodo => axios.post('/api/todos', newTodo),
onMutate: async newTodo => {
await queryClient.cancelQueries(['todos'])
const prev = queryClient.getQueryData(['todos'])
queryClient.setQueryData(['todos'], old => [...old, newTodo])
return { prev }
},
onError: (err, vars, context) => {
queryClient.setQueryData(['todos'], context.prev)
},
onSettled: () => {
queryClient.invalidateQueries(['todos'])
}
})Beyond these, TanStack Query Vue also supports polling, refetch on window focus, offline support, and scroll restoration.
Debugging with @tanstack/vue-query-devtools
Enable the devtools with a single line:
import { VueQueryDevTools } from '@tanstack/vue-query-devtools'
app.use(VueQueryDevTools)Live view of cache keys, data, and expiration.
One‑click refetch or invalidate.
Dark / light theme support, far more convenient than console logging.
Conclusion
Axios remains a solid HTTP client, but for today’s increasingly complex data‑layer requirements, TanStack Query Vue turns data fetching, caching, and refreshing into a configuration‑driven workflow. From simple lists to enterprise‑grade middle‑platforms, ten lines of code can replace the hundred‑line manual Axios implementations, letting developers focus on business logic instead of boilerplate.
Official documentation (Chinese):
https://tanstack.com.cn/query/latest/docs/framework/vue/overviewSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Cultivation Path
Focused on sharing practical tech content about TypeScript, Vue 3, front-end architecture, and source code analysis.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
