Watch and computed usage of vue3 (compared to vue2)

1. Difference between watch and computed

# watch computed
consume Do not use the cache (consume a lot of resources) Cache by default (low resource consumption)
trigger Asynchronous support Async is not supported
monitor One-to-many (or one-to-one) Many-to-one (or one-to-one)

2. Comparison of vue2 and 3 using (watch and computed)

Ⅰ.vue3 's use of watch and computed =>

import {
    
    watch,computed} from 'vue'
setup(){
    
    
    
    const num = ref (1);
    watch(num,(newValue,oldValue)=>{
    
      console.log(newValue,oldValue); });  (多对一)改变后可进行多步操作
    
    //-------------------------------------------------------------------------
    
    const  width  =  ref(2);
    const  height =  ref(2);
    let S = computed(()=>{
    
    return width.value * height.value }});           (一对多)其中一个方式改变就会触发
}

Ⅱ.vue2 's use of watch and computed =>

watch:{
    
      // (aaa为data中参数)  改变就执行 影响一或多 (多对一)   默认走缓存
    'aaa': function(newVal,oldVal){
    
     console.log(newVal,oldVal);}
}
//--------------------------------------------------------------
computed:{
    
    
    Numchange(){
    
    
        return  this.Num * this.price ;   其中一个依赖改变 Numchange 改变  (一对多)
    }
}

3. Extend vue3 and add watchEffect (difference from vue2)

Ⅰ. The object wrapped with ref or reactive in watchEffect will be executed when the value changes, no need to write the monitoring item.
Ⅱ. If watch wants to monitor more than one, it must be in the form of an array or an object.

setup(){
    
    
    watch([a,b],(newArr,oldArr)=>{
    
      console.log(newArr,oldArr) });
    
    watchEffect(()=>{
    
      console.log(a,b));  })
    // 只监听ref 和 reactive 且出现在回调函数中的对象
}

Guess you like

Origin blog.csdn.net/weixin_42232622/article/details/125451879