What is watch effect

person github

watchEffectis a Composition API function in Vue 3, used to run a function immediately and track its dependencies responsively. The function is automatically re-run when a dependency (reactive reference or computed property) changes.

This is somewhat different from Vue 2 watch, as it watchis typically used to observe a single reactive property or computed property, while watchEffectmultiple reactive dependencies can be tracked automatically.

Basic usage

import {
    
     ref, watchEffect } from 'vue';

export default {
    
    
  setup() {
    
    
    const count = ref(0);
    const doubled = ref(0);

    watchEffect(() => {
    
    
      console.log(`count is: ${
      
      count.value}`);  // 自动追踪 count
      doubled.value = count.value * 2;  // 自动追踪 doubled
    });

    return {
    
    
      count,
      doubled
    };
  }
}

In this example, watchEffectit is run once immediately and re-run whenever countor doubledchanges.

stop observing

watchEffectReturns a function to stop observing. You can call this function to stop observing:

const stopWatch = watchEffect(() => {
    
    
  // 你的代码
});

// 停止观察
stopWatch();

watchComparison with

  • watchEffectMore automatic and convenient because it automatically tracks all reactive dependencies.
  • watchMore flexible as it allows you to observe a single reactive reference or computed property and provide the old and new values.

Which one you choose depends on your specific needs. If you need more control and flexibility, you might choose watch. If you want a simpler and automatic solution, this watchEffectmight suit you better.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/132841377