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

92 lines
2.2 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'
import { ReactiveFlags, toRaw } from './reactive'
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>
}
class ComputedRefImpl<T> {
private _value!: T
private _dirty = true
public readonly effect: ReactiveEffect<T>
public readonly __v_isRef = true;
public readonly [ReactiveFlags.IS_READONLY]: boolean
constructor(
getter: ComputedGetter<T>,
private readonly _setter: ComputedSetter<T>,
isReadonly: boolean
) {
this.effect = effect(getter, {
lazy: true,
scheduler: () => {
if (!this._dirty) {
this._dirty = true
trigger(toRaw(this), TriggerOpTypes.SET, 'value')
}
}
})
this[ReactiveFlags.IS_READONLY] = isReadonly
}
get value() {
if (this._dirty) {
this._value = this.effect()
this._dirty = false
}
track(toRaw(this), TrackOpTypes.GET, 'value')
return this._value
}
set value(newValue: T) {
this._setter(newValue)
}
}
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
}
return new ComputedRefImpl(
getter,
setter,
isFunction(getterOrOptions) || !getterOrOptions.set
) as any
2018-09-19 23:35:38 +08:00
}