/
index.ts
61 lines (54 loc) · 1.53 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
60
61
import type { ToRefs } from 'vue-demi'
import { toRefs as _toRefs, customRef, isRef } from 'vue-demi'
import { toValue } from '../toValue'
import type { MaybeRef, MaybeRefOrGetter } from '../utils'
export interface ToRefsOptions {
/**
* Replace the original ref with a copy on property update.
*
* @default true
*/
replaceRef?: MaybeRefOrGetter<boolean>
}
/**
* Extended `toRefs` that also accepts refs of an object.
*
* @see https://vueuse.org/toRefs
* @param objectRef A ref or normal object or array.
*/
export function toRefs<T extends object>(
objectRef: MaybeRef<T>,
options: ToRefsOptions = {},
): ToRefs<T> {
if (!isRef(objectRef))
return _toRefs(objectRef)
const result: any = Array.isArray(objectRef.value)
? Array.from({ length: objectRef.value.length })
: {}
for (const key in objectRef.value) {
result[key] = customRef<T[typeof key]>(() => ({
get() {
return objectRef.value[key]
},
set(v) {
const replaceRef = toValue(options.replaceRef) ?? true
if (replaceRef) {
if (Array.isArray(objectRef.value)) {
const copy: any = [...objectRef.value]
copy[key] = v
objectRef.value = copy
}
else {
const newObject = { ...objectRef.value, [key]: v }
Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value))
objectRef.value = newObject
}
}
else {
objectRef.value[key] = v
}
},
}))
}
return result
}