The implementation of computed properties
Core Concepts of Computed Properties
Vue3's computed
is a key part of the reactivity system. It automatically calculates and caches results based on reactive dependencies. When dependencies change, the computed property re-evaluates; otherwise, it returns the cached value. This mechanism avoids unnecessary repeated calculations, improving performance.
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
Implementation Principles of Computed Properties
The implementation of computed properties primarily relies on the ComputedRefImpl
class, which inherits from Ref
and possesses reactive characteristics. The core logic revolves around the getter
function, dependency tracking, and caching mechanisms.
class ComputedRefImpl<T> {
private _value!: T
private _dirty = true
private _dep?: Dep
public readonly effect: ReactiveEffect<T>
constructor(getter: ComputedGetter<T>) {
this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) {
this._dirty = true
triggerRefValue(this)
}
})
this.effect.computed = this
}
get value() {
trackRefValue(this)
if (this._dirty) {
this._dirty = false
this._value = this.effect.run()!
}
return this._value
}
}
Dependency Tracking and Update Triggering
Computed properties manage dependencies through trackRefValue
and triggerRefValue
. When accessing a computed property, the current active effect is collected as a dependency. When dependencies change, the scheduler function is triggered.
// Simplified dependency tracking
function trackRefValue(ref: ComputedRefImpl<any>) {
if (activeEffect) {
trackEffects(ref.dep || (ref.dep = createDep()))
}
}
// Simplified update triggering
function triggerRefValue(ref: ComputedRefImpl<any>) {
if (ref.dep) {
triggerEffects(ref.dep)
}
}
Caching Mechanism and Dirty Checking
The _dirty
flag controls caching logic. Initially set to true
, it indicates the need for recalculation. After calculation, it is set to false
. When dependencies change, the scheduler resets _dirty
to true
, triggering recalculation upon the next access.
// Example: Caching behavior verification
const price = ref(10)
const tax = computed(() => price.value * 0.2)
console.log(tax.value) // Calculates and caches result 2.0
price.value = 20 // Marks as dirty but doesn't recalculate immediately
console.log(tax.value) // Recalculates to get 4.0
Advanced Usage of Computed Properties
Computed properties support setters, enabling writable computed properties. Internally, customRef
or shallowRef
handles more complex scenarios.
const fullName = computed({
get() {
return `${firstName.value} ${lastName.value}`
},
set(newValue) {
[firstName.value, lastName.value] = newValue.split(' ')
}
})
Synergy with watch
Computed properties often work with watch
, but they differ fundamentally. Computed properties are declarative derived values, while watch
is imperative for side effects.
const user = reactive({ firstName: 'John', lastName: 'Doe' })
// Computed property
const fullName = computed(() => `${user.firstName} ${user.lastName}`)
// watch
watch(() => user.firstName, (newVal) => {
console.log(`First name changed to ${newVal}`)
})
Performance Optimization Strategies
The lazy evaluation feature of computed properties offers performance advantages. Vue3 implements intelligent updates through the effect
scheduler, avoiding unnecessary calculations.
// Scheduler optimization example
const scheduler = () => {
if (!this._dirty) {
this._dirty = true
triggerRefValue(this)
}
}
this.effect = new ReactiveEffect(getter, scheduler)
Comparison with Vue2 Implementation
Vue3's computed properties have significant improvements:
- Proxy-based reactivity system
- More granular dependency tracking
- Better integration with the Composition API
- Enhanced type support
// Vue2 implementation comparison
Vue2: {
computed: {
double() {
return this.count * 2
}
}
}
// Vue3 implementation
const double = computed(() => count.value * 2)
Practical Application Scenarios
Computed properties are suitable for:
- Complex data transformations
- Filtering/sorting lists
- Form validation states
- Conditional style calculations
// Shopping cart total calculation
const cart = reactive({
items: [
{ price: 10, quantity: 2 },
{ price: 15, quantity: 1 }
],
discount: 0.1
})
const total = computed(() => {
return cart.items.reduce((sum, item) =>
sum + item.price * item.quantity, 0
) * (1 - cart.discount)
})
Source Code Structure Analysis
Computed property-related code is mainly located in:
packages/reactivity/src/computed.ts
- Core implementationpackages/reactivity/src/effect.ts
- Dependency managementpackages/reactivity/src/reactive.ts
- Basic reactivity APIs
Key function call chain:
computed()
→ new ComputedRefImpl()
→ ReactiveEffect
→ track/trigger
Debugging Techniques and Practices
During development, computed properties can be debugged using:
onTrack
andonTrigger
hooks- Checking
_dirty
state in Chrome DevTools - Adding logs for dependency changes
const debugComputed = computed(() => {
// Calculation logic
}, {
onTrack(e) {
console.log('Dependency tracked', e)
},
onTrigger(e) {
console.log('Dependency triggered update', e)
}
})
Edge Case Handling
Computed properties need to handle special scenarios:
- Circular dependency detection
- Synchronous modification of dependencies
- Errors during calculation
- Behavior in SSR environments
// Error handling example
const riskyComputed = computed(() => {
try {
return someOperation()
} catch (e) {
console.error('Calculation failed', e)
return fallbackValue
}
})
Comparison with React's useMemo
Although conceptually similar, Vue's computed properties have notable differences:
- Automatic dependency tracking
- Deeper integration
- Native reactivity system support
- Smarter caching strategies
// React comparison
function Component() {
const [count, setCount] = useState(0)
const double = useMemo(() => count * 2, [count])
// ...
}
// Vue equivalent
const count = ref(0)
const double = computed(() => count.value * 2)
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:数组的特殊响应处理