/
index.ts
54 lines (48 loc) · 1.42 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
import type { Ref, ShallowUnwrapRef } from 'vue-demi'
import { isRef } from 'vue-demi'
import { __onlyVue27Plus } from '../utils/compatibility'
export interface ExtendRefOptions<Unwrap extends boolean = boolean> {
/**
* Is the extends properties enumerable
*
* @default false
*/
enumerable?: boolean
/**
* Unwrap for Ref properties
*
* @default true
*/
unwrap?: Unwrap
}
/**
* Overload 1: Unwrap set to false
*/
export function extendRef<R extends Ref<any>, Extend extends object, Options extends ExtendRefOptions<false>>(ref: R, extend: Extend, options?: Options): ShallowUnwrapRef<Extend> & R
/**
* Overload 2: Unwrap unset or set to true
*/
export function extendRef<R extends Ref<any>, Extend extends object, Options extends ExtendRefOptions>(ref: R, extend: Extend, options?: Options): Extend & R
// implementation
export function extendRef<R extends Ref<any>, Extend extends object>(ref: R, extend: Extend, { enumerable = false, unwrap = true }: ExtendRefOptions = {}) {
__onlyVue27Plus()
for (const [key, value] of Object.entries(extend)) {
if (key === 'value')
continue
if (isRef(value) && unwrap) {
Object.defineProperty(ref, key, {
get() {
return value.value
},
set(v) {
value.value = v
},
enumerable,
})
}
else {
Object.defineProperty(ref, key, { value, enumerable })
}
}
return ref
}