如果您发现自己希望出于任何原因,您可以为整个应用程序共享相同的查询函数,并且仅使用查询键来标识它应该获取什么,您可以通过为 TanStack Query 提供一个 默认查询函数 来做到这一点
// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com${queryKey[0]}`,
)
return data
}
// provide the default query function to your app with defaultOptions
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: { queries: { queryFn: defaultQueryFn } },
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
// All you have to do now is pass a key!
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
})
// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
const { data } = await axios.get(
`https://jsonplaceholder.typicode.com${queryKey[0]}`,
)
return data
}
// provide the default query function to your app with defaultOptions
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: { queries: { queryFn: defaultQueryFn } },
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
// All you have to do now is pass a key!
const { status, data, error, isFetching } = useQuery({
queryKey: [`/posts/${postId}`],
})
如果您想覆盖默认的 queryFn,您可以像平常一样提供您自己的。