Skip to content

Commit 8874b21

Browse files
authored
perf(reactivity): better computed tracking (#710)
1 parent fc7bcca commit 8874b21

File tree

1 file changed

+10
-20
lines changed

1 file changed

+10
-20
lines changed

packages/reactivity/src/computed.ts

+10-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { effect, ReactiveEffect, activeEffect } from './effect'
1+
import { effect, ReactiveEffect, trigger, track } from './effect'
2+
import { TriggerOpTypes, TrackOpTypes } from './operations'
23
import { Ref, UnwrapRef } from './ref'
34
import { isFunction, NOOP } from '@vue/shared'
45

@@ -42,16 +43,20 @@ export function computed<T>(
4243

4344
let dirty = true
4445
let value: T
46+
let computed: ComputedRef<T>
4547

4648
const runner = effect(getter, {
4749
lazy: true,
4850
// mark effect as computed so that it gets priority during trigger
4951
computed: true,
5052
scheduler: () => {
51-
dirty = true
53+
if (!dirty) {
54+
dirty = true
55+
trigger(computed, TriggerOpTypes.SET, 'value')
56+
}
5257
}
5358
})
54-
return {
59+
computed = {
5560
_isRef: true,
5661
// expose effect so computed can be stopped
5762
effect: runner,
@@ -60,27 +65,12 @@ export function computed<T>(
6065
value = runner()
6166
dirty = false
6267
}
63-
// When computed effects are accessed in a parent effect, the parent
64-
// should track all the dependencies the computed property has tracked.
65-
// This should also apply for chained computed properties.
66-
trackChildRun(runner)
68+
track(computed, TrackOpTypes.GET, 'value')
6769
return value
6870
},
6971
set value(newValue: T) {
7072
setter(newValue)
7173
}
7274
} as any
73-
}
74-
75-
function trackChildRun(childRunner: ReactiveEffect) {
76-
if (activeEffect === undefined) {
77-
return
78-
}
79-
for (let i = 0; i < childRunner.deps.length; i++) {
80-
const dep = childRunner.deps[i]
81-
if (!dep.has(activeEffect)) {
82-
dep.add(activeEffect)
83-
activeEffect.deps.push(dep)
84-
}
85-
}
75+
return computed
8676
}

0 commit comments

Comments
 (0)