阿里云主机折上折
  • 微信号
Current Site:Index > The implementation of computed properties

The implementation of computed properties

Author:Chuan Chen 阅读数:50235人阅读 分类: Vue.js

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:

  1. Proxy-based reactivity system
  2. More granular dependency tracking
  3. Better integration with the Composition API
  4. 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:

  1. Complex data transformations
  2. Filtering/sorting lists
  3. Form validation states
  4. 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:

  1. packages/reactivity/src/computed.ts - Core implementation
  2. packages/reactivity/src/effect.ts - Dependency management
  3. packages/reactivity/src/reactive.ts - Basic reactivity APIs

Key function call chain: computed()new ComputedRefImpl()ReactiveEffecttrack/trigger

Debugging Techniques and Practices

During development, computed properties can be debugged using:

  1. onTrack and onTrigger hooks
  2. Checking _dirty state in Chrome DevTools
  3. 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:

  1. Circular dependency detection
  2. Synchronous modification of dependencies
  3. Errors during calculation
  4. 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:

  1. Automatic dependency tracking
  2. Deeper integration
  3. Native reactivity system support
  4. 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

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.