默认查询函数

如果您发现自己因为任何原因希望为整个应用程序共享同一个查询函数,而只需要使用查询键来标识它应该获取什么,那么您可以通过为 TanStack Query 提供一个默认查询函数来实现。

tsx
// 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,您只需像往常一样提供自己的查询函数即可。