Skip to main content

自定义客户端

自定义客户端

Vue Query允许为Vue上下文提供自定义的QueryClient

当您需要预先创建QueryClient并将其与无法访问Vue上下文的其他库集成时,这可能非常方便。

因此,VueQueryPlugin接受QueryClientConfigQueryClient作为插件选项。

如果您提供QueryClientConfig,则QueryClient实例将在内部创建并提供给Vue上下文。

const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: { queries: { staleTime: 3600 } },
},
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
const myClient = new QueryClient(queryClientConfig)
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClient: myClient,
}
app.use(VueQueryPlugin, vueQueryPluginOptions)

自定义上下文键名

您还可以自定义QueryClient在Vue上下文中的键名。如果您希望在同一页上避免多个Vue应用之间的名称冲突,这可能很有用。

它适用于默认的QueryClient和自定义的QueryClient

const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientKey: 'Foo',
}
app.use(VueQueryPlugin, vueQueryPluginOptions)
const myClient = new QueryClient(queryClientConfig)
const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClient: myClient,
queryClientKey: 'Foo',
}
app.use(VueQueryPlugin, vueQueryPluginOptions)

要使用自定义的客户端键名,您必须在查询选项中提供它。

useQuery({
queryKey: ['query1'],
queryFn: fetcher,
queryClientKey: 'foo',
})

在内部,自定义键名将与默认的查询键名组合成后缀。但用户不必担心这个。

const vueQueryPluginOptions: VueQueryPluginOptions = {
queryClientKey: 'Foo',
}
app.use(VueQueryPlugin, vueQueryPluginOptions) // -> VUE_QUERY_CLIENT:Foo