Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

vueQueryPlugin.ts

106 lines2.7 KB

1import { isVue2 } from 'vue-demi'
2import type { QueryClientConfig } from '@tanstack/query-core'
3​
4import { QueryClient } from './queryClient'
5import { getClientKey } from './utils'
6import { setupDevtools } from './devtools/devtools'
7import type { MaybeRefDeep } from './types'
8​
9declare global {
10 interface Window {
11 __VUE_QUERY_CONTEXT__?: QueryClient
12 }
14​
15export interface AdditionalClient {
16 queryClient: QueryClient
17 queryClientKey: string
19​
20interface ConfigOptions {
21 queryClientConfig?: MaybeRefDeep<QueryClientConfig>
22 queryClientKey?: string
23 contextSharing?: boolean
25​
26interface ClientOptions {
27 queryClient?: QueryClient
28 queryClientKey?: string
29 contextSharing?: boolean
31​
32export type VueQueryPluginOptions = ConfigOptions | ClientOptions
33​
34export const VueQueryPlugin = {
35 install: (app: any, options: VueQueryPluginOptions = {}) => {
36 const clientKey = getClientKey(options.queryClientKey)
37 let client: QueryClient
38​
39 if ('queryClient' in options && options.queryClient) {
40 client = options.queryClient
41 } else {
42 if (options.contextSharing && typeof window !== 'undefined') {
43 if (!window.__VUE_QUERY_CONTEXT__) {
44 const clientConfig =
45 'queryClientConfig' in options
46 ? options.queryClientConfig
47 : undefined
48 client = new QueryClient(clientConfig)
49 window.__VUE_QUERY_CONTEXT__ = client
50 } else {
51 client = window.__VUE_QUERY_CONTEXT__
52 }
53 } else {
54 const clientConfig =
55 'queryClientConfig' in options ? options.queryClientConfig : undefined
56 client = new QueryClient(clientConfig)
57 }
58 }
59​
60 client.mount()
61​
62 const cleanup = () => {
63 client.unmount()
64 }
65​
66 if (app.onUnmount) {
67 app.onUnmount(cleanup)
68 } else {
69 const originalUnmount = app.unmount
70 app.unmount = function vueQueryUnmount() {
71 cleanup()
72 originalUnmount()
73 }
74 }
75​
76 /* istanbul ignore next */
77 if (isVue2) {
78 app.mixin({
79 beforeCreate() {
80 // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/master/src/apis/inject.ts#L30
81 if (!this._provided) {
82 const provideCache = {}
83 Object.defineProperty(this, '_provided', {
84 get: () => provideCache,
85 set: (v) => Object.assign(provideCache, v),
86 })
87 }
88​
89 this._provided[clientKey] = client
90​
91 if (process.env.NODE_ENV === 'development') {
92 if (this === this.$root) {
93 setupDevtools(this, client)
94 }
95 }
96 },
97 })
98 } else {
99 app.provide(clientKey, client)
100​
101 if (process.env.NODE_ENV === 'development') {
102 setupDevtools(app, client)
103 }
104 }
105 },