vue3的watch、computed写法及扩展( 对比vue2)

1.watch和computed区别

# watch computed
消耗 不走缓存 (消耗资源大) 默认走缓存 (消耗资源小)
触发 支持异步 不支持异步
监听 一对多 (或一对一) 多对一 (或一对一)

2. 使用( watch 和 computed ) vue2和3对比

Ⅰ.vue3 对 watch 和 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 对 watch 和 computed 的使用 =>

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

3.扩展 vue3 新增 watchEffect (与vue2的区别)

Ⅰ. watchEffect中用 ref 或reactive 包裹的对象,值发生变化就会执行,不需要写监听项。
Ⅱ. watch想监听多个,必须形成数组或对象的形式。

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

你可能感兴趣的:(入坑vue3,vue.js,前端)