perf(reactivity): avoid triggering re-render if computed value did not change

This commit is contained in:
Evan You 2021-07-06 22:01:59 -04:00
parent f5617fc3bb
commit ebaac9a56d
3 changed files with 41 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import { ReactiveFlags, toRaw } from './reactive'
export interface ComputedRef<T = any> extends WritableComputedRef<T> { export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T readonly value: T
defer?: (fn: () => void) => void
} }
export interface WritableComputedRef<T> extends Ref<T> { export interface WritableComputedRef<T> extends Ref<T> {
@ -19,6 +20,16 @@ export interface WritableComputedOptions<T> {
set: ComputedSetter<T> set: ComputedSetter<T>
} }
type ComputedScheduler = (fn: () => void) => void
let scheduler: ComputedScheduler | undefined
/**
* Set a scheduler for deferring computed computations
*/
export const setComputedScheduler = (s: ComputedScheduler | undefined) => {
scheduler = s
}
class ComputedRefImpl<T> { class ComputedRefImpl<T> {
public dep?: Set<ReactiveEffect> = undefined public dep?: Set<ReactiveEffect> = undefined
@ -35,11 +46,35 @@ class ComputedRefImpl<T> {
private readonly _setter: ComputedSetter<T>, private readonly _setter: ComputedSetter<T>,
isReadonly: boolean isReadonly: boolean
) { ) {
let deferFn: () => void
let scheduled = false
this.effect = new ReactiveEffect(getter, () => { this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) { if (!this._dirty) {
this._dirty = true this._dirty = true
if (scheduler) {
if (!scheduled) {
scheduled = true
scheduler(
deferFn ||
(deferFn = () => {
scheduled = false
if (this._dirty) {
this._dirty = false
const newValue = this.effect.run()!
if (this._value !== newValue) {
this._value = newValue
triggerRefValue(this) triggerRefValue(this)
} }
} else {
triggerRefValue(this)
}
})
)
}
} else {
triggerRefValue(this)
}
}
}) })
this[ReactiveFlags.IS_READONLY] = isReadonly this[ReactiveFlags.IS_READONLY] = isReadonly
} }

View File

@ -30,6 +30,7 @@ export {
} from './reactive' } from './reactive'
export { export {
computed, computed,
setComputedScheduler,
ComputedRef, ComputedRef,
WritableComputedRef, WritableComputedRef,
WritableComputedOptions, WritableComputedOptions,

View File

@ -2,6 +2,10 @@ import { ErrorCodes, callWithErrorHandling } from './errorHandling'
import { isArray } from '@vue/shared' import { isArray } from '@vue/shared'
import { ComponentInternalInstance, getComponentName } from './component' import { ComponentInternalInstance, getComponentName } from './component'
import { warn } from './warning' import { warn } from './warning'
import { setComputedScheduler } from '@vue/reactivity'
// set scheduler for computed
setComputedScheduler(queueJob)
export interface SchedulerJob extends Function { export interface SchedulerJob extends Function {
id?: number id?: number