-
Notifications
You must be signed in to change notification settings - Fork 343
/
computed.ts
56 lines (48 loc) · 1.37 KB
/
computed.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
import { getCurrentVue, getCurrentVM } from '../runtimeContext'
import { createRef, Ref } from '../reactivity'
import { defineComponentInstance } from '../helper'
import { warn } from '../utils'
interface Option<T> {
get: () => T
set: (value: T) => void
}
export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T
}
export interface WritableComputedRef<T> extends Ref<T> {}
// read-only
export function computed<T>(getter: Option<T>['get']): ComputedRef<T>
// writable
export function computed<T>(options: Option<T>): WritableComputedRef<T>
// implement
export function computed<T>(
options: Option<T>['get'] | Option<T>
): ComputedRef<T> | WritableComputedRef<T> {
const vm = getCurrentVM()
let get: Option<T>['get'], set: Option<T>['set'] | undefined
if (typeof options === 'function') {
get = options
} else {
get = options.get
set = options.set
}
const computedHost = defineComponentInstance(getCurrentVue(), {
computed: {
$$state: {
get,
set,
},
},
})
vm && vm.$on('hook:destroyed', () => computedHost.$destroy())
return createRef<T>({
get: () => (computedHost as any).$$state,
set: (v: T) => {
if (__DEV__ && !set) {
warn('Computed property was assigned to but it has no setter.', vm!)
return
}
;(computedHost as any).$$state = v
},
})
}