Skip to content

Commit

Permalink
perf(reactivity): avoid triggering re-render if computed value did no…
Browse files Browse the repository at this point in the history
…t change
  • Loading branch information
yyx990803 committed Jul 16, 2021
1 parent f5617fc commit ebaac9a
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
37 changes: 36 additions & 1 deletion packages/reactivity/src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ReactiveFlags, toRaw } from './reactive'

export interface ComputedRef<T = any> extends WritableComputedRef<T> {
readonly value: T
defer?: (fn: () => void) => void
}

export interface WritableComputedRef<T> extends Ref<T> {
Expand All @@ -19,6 +20,16 @@ export interface WritableComputedOptions<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> {
public dep?: Set<ReactiveEffect> = undefined

Expand All @@ -35,10 +46,34 @@ class ComputedRefImpl<T> {
private readonly _setter: ComputedSetter<T>,
isReadonly: boolean
) {
let deferFn: () => void
let scheduled = false
this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) {
this._dirty = true
triggerRefValue(this)
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)
}
} else {
triggerRefValue(this)
}
})
)
}
} else {
triggerRefValue(this)
}
}
})
this[ReactiveFlags.IS_READONLY] = isReadonly
Expand Down
1 change: 1 addition & 0 deletions packages/reactivity/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export {
} from './reactive'
export {
computed,
setComputedScheduler,
ComputedRef,
WritableComputedRef,
WritableComputedOptions,
Expand Down
4 changes: 4 additions & 0 deletions packages/runtime-core/src/scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { ErrorCodes, callWithErrorHandling } from './errorHandling'
import { isArray } from '@vue/shared'
import { ComponentInternalInstance, getComponentName } from './component'
import { warn } from './warning'
import { setComputedScheduler } from '@vue/reactivity'

// set scheduler for computed
setComputedScheduler(queueJob)

export interface SchedulerJob extends Function {
id?: number
Expand Down

0 comments on commit ebaac9a

Please sign in to comment.