vue3-yuanma/packages/reactivity/src/computed.ts

77 lines
1.9 KiB
TypeScript
Raw Normal View History

import { effect, ReactiveEffect, trigger, track } from './effect'
import { TriggerOpTypes, TrackOpTypes } from './operations'
import { Ref } from './ref'
import { isFunction, NOOP } from '@vue/shared'
2018-09-19 23:35:38 +08:00
export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T
2018-09-19 23:35:38 +08:00
}
2019-10-05 22:10:37 +08:00
export interface WritableComputedRef<T> extends Ref<T> {
readonly effect: ReactiveEffect<T>
}
export type ComputedGetter<T> = (ctx?: any) => T
2019-10-22 01:57:20 +08:00
export type ComputedSetter<T> = (v: T) => void
export interface WritableComputedOptions<T> {
2019-10-22 01:57:20 +08:00
get: ComputedGetter<T>
set: ComputedSetter<T>
}
2019-10-22 01:57:20 +08:00
export function computed<T>(getter: ComputedGetter<T>): ComputedRef<T>
2019-06-06 12:35:49 +08:00
export function computed<T>(
options: WritableComputedOptions<T>
): WritableComputedRef<T>
export function computed<T>(
2019-10-22 01:57:20 +08:00
getterOrOptions: ComputedGetter<T> | WritableComputedOptions<T>
2019-10-22 23:26:48 +08:00
) {
let getter: ComputedGetter<T>
let setter: ComputedSetter<T>
if (isFunction(getterOrOptions)) {
getter = getterOrOptions
setter = __DEV__
? () => {
console.warn('Write operation failed: computed value is readonly')
}
: NOOP
} else {
getter = getterOrOptions.get
setter = getterOrOptions.set
}
let dirty = true
let value: T
let computed: ComputedRef<T>
2019-06-06 12:35:49 +08:00
const runner = effect(getter, {
2018-09-19 23:35:38 +08:00
lazy: true,
2019-05-29 23:44:59 +08:00
// mark effect as computed so that it gets priority during trigger
computed: true,
2018-09-19 23:35:38 +08:00
scheduler: () => {
if (!dirty) {
dirty = true
trigger(computed, TriggerOpTypes.SET, 'value')
}
2018-09-19 23:35:38 +08:00
}
})
computed = {
__v_isRef: true,
2019-05-29 18:44:50 +08:00
// expose effect so computed can be stopped
effect: runner,
get value() {
if (dirty) {
value = runner()
dirty = false
}
track(computed, TrackOpTypes.GET, 'value')
2019-05-29 18:44:50 +08:00
return value
2019-06-06 12:35:49 +08:00
},
set value(newValue: T) {
setter(newValue)
2019-05-29 18:44:50 +08:00
}
} as any
return computed
2018-09-19 23:35:38 +08:00
}