vue3中watch 和watchEffect的用法

watch 和 watchEffect 都是监听器,但在写法和使用上有所区别。

watch在监听ref和reactive类型时watch函数的写法不同。

1.1、 watch监听ref类型时:

import {ref, watch} from 'vue'
export default {
    setup(){
        const state = ref(0)

        watch(state, (newValue, oldValue) => {
          console.log(`原值为${oldValue}`)
          console.log(`新值为${newValue}`)
          /* 1秒后打印结果:
                  原值为0
                  新值为1
          */
        })

        // 1秒后将state值+1
        setTimeout(() => {
          state.value ++
        }, 1000)
    }
}

1.2 watch监听reactive类型时:

import {ref, watch} from 'vue'
export default {
    setup(){
        const person = reactive({age: 17,name: 'Rose'})

        watch(()=>person.age, (newValue, oldValue) => {
          console.log(`原值为${oldValue}`)
          console.log(`新值为${newValue}`)
          /* 1秒后打印结果:
                  原值为18
                  新值为19
          */
        })

        // 1秒后将state值+1
        setTimeout(() => {
          person.age ++
        }, 1000)
    }
}

1.3 watch还有第三个参数 是一个对象,可以进行一些配置

这样配置就不是惰性的了,首次展示也会运行。

{immeddiate:true}

1.4 watch 同时监听多个参数

import {ref,reactive,watch} from 'vue'
export default {
    setup(){
        const value1 = ref('0')
        const value2 = ref ('1')
        const person = reactive({age: 18,name: 'Rose'})

        watch([value1,value2],([cur1,pre1],[cur2,pre2])=>{})

        watch([()=>person.age,[()=>person.name],([cur1,pre1],[cur2,pre2])=>{})
    }
    
}

2.1 watchEffect的用法

import {ref, watchEffect} from 'vue'
export default {
    setup(){
        const person = reactive({age: 17,name: 'Rose'})
        const state = ref('0')
        watchEffect(()=>{console.log(state.value)})

        watchEffect(()=>{console.log(person.age)})
        // 1秒后将state值+1
        setTimeout(() => {
          person.age ++
          state.value++
        }, 1000)
    }
}

3、 vue3兼容Vue2,所有vue3 中可以使用Vue2 中watch的用法

import {ref,watchEffect} from 'vue'
export default {
    setup(){
        const state = ref('0')
        watchEffect(()=>{console.log(state.value)})
    },
    watch:{
        state(newVal,oldVal){
            console.log(newVal,oldVal)
        }
    }
}

虽然vue3兼容Vue2 中watch的用法,但是steup外无法调用steup内部的函数,这里的watch并没有太大的意义

4、watch和wacthEffect的区别

  • 不需要手动传入依赖
  • 每次初始化时会执行一次回调函数来自动获取依赖
  • 无法获取到原值,只能得到变化后的值
  • watchEffect会在初始化的时候执行,watch不会
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值