-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
index.ts
59 lines (54 loc) · 1.89 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import type { ComputedRef, InjectionKey } from 'vue-demi'
import { computed, inject } from 'vue-demi'
export type ComputedInjectGetter<T, K> = (source: T | undefined, ctx?: any) => K
export type ComputedInjectGetterWithDefault<T, K> = (source: T, ctx?: any) => K
export type ComputedInjectSetter<T> = (v: T) => void
export interface WritableComputedInjectOptions<T, K> {
get: ComputedInjectGetter<T, K>
set: ComputedInjectSetter<K>
}
export interface WritableComputedInjectOptionsWithDefault<T, K> {
get: ComputedInjectGetterWithDefault<T, K>
set: ComputedInjectSetter<K>
}
export function computedInject<T, K = any>(
key: InjectionKey<T> | string,
getter: ComputedInjectGetter<T, K>
): ComputedRef<K | undefined>
export function computedInject<T, K = any>(
key: InjectionKey<T> | string,
options: WritableComputedInjectOptions<T, K>
): ComputedRef<K | undefined>
export function computedInject<T, K = any>(
key: InjectionKey<T> | string,
getter: ComputedInjectGetterWithDefault<T, K>,
defaultSource: T,
treatDefaultAsFactory?: false
): ComputedRef<K>
export function computedInject<T, K = any>(
key: InjectionKey<T> | string,
options: WritableComputedInjectOptionsWithDefault<T, K>,
defaultSource: T | (() => T),
treatDefaultAsFactory: true
): ComputedRef<K>
export function computedInject<T, K = any>(
key: InjectionKey<T> | string,
options: ComputedInjectGetter<T, K> | WritableComputedInjectOptions<T, K>,
defaultSource?: T | (() => T),
treatDefaultAsFactory?: boolean,
) {
let source = inject(key) as T | undefined
if (defaultSource)
source = inject(key, defaultSource as T) as T
if (treatDefaultAsFactory)
source = inject(key, defaultSource, treatDefaultAsFactory) as T
if (typeof options === 'function') {
return computed(ctx => options(source, ctx))
}
else {
return computed({
get: ctx => options.get(source, ctx),
set: options.set,
})
}
}