/
storeToRefs.ts
63 lines (58 loc) 路 1.56 KB
/
storeToRefs.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
60
61
62
63
import {
ComputedRef,
isReactive,
isRef,
isVue2,
Ref,
toRaw,
ToRef,
toRef,
ToRefs,
toRefs,
} from 'vue-demi'
import { StoreGetters, StoreState } from './store'
import type { PiniaCustomStateProperties, StoreGeneric } from './types'
type ToComputedRefs<T> = {
[K in keyof T]: ToRef<T[K]> extends Ref<infer U>
? ComputedRef<U>
: ToRef<T[K]>
}
/**
* Extracts the return type for `storeToRefs`.
* Will convert any `getters` into `ComputedRef`.
*/
export type StoreToRefs<SS extends StoreGeneric> = ToRefs<
StoreState<SS> & PiniaCustomStateProperties<StoreState<SS>>
> &
ToComputedRefs<StoreGetters<SS>>
/**
* Creates an object of references with all the state, getters, and plugin-added
* state properties of the store. Similar to `toRefs()` but specifically
* designed for Pinia stores so methods and non reactive properties are
* completely ignored.
*
* @param store - store to extract the refs from
*/
export function storeToRefs<SS extends StoreGeneric>(
store: SS
): StoreToRefs<SS> {
// See https://github.com/vuejs/pinia/issues/852
// It's easier to just use toRefs() even if it includes more stuff
if (isVue2) {
// @ts-expect-error: toRefs include methods and others
return toRefs(store)
} else {
store = toRaw(store)
const refs = {} as StoreToRefs<SS>
for (const key in store) {
const value = store[key]
if (isRef(value) || isReactive(value)) {
// @ts-expect-error: the key is state or getter
refs[key] =
// ---
toRef(store, key)
}
}
return refs
}
}