vue3 watch

2024-01-03  本文已影响0人  糖醋里脊120625
1.子组件中监听传入的数据
watch(
  () => props.testStr,
  (newVal, oldVal) => {
    console.log('监听基本类型数据testStr')
    console.log('new', newVal)
    console.log('old', oldVal)
  }
),
************************************************************************
2,深度监听
watch(routeName,(newVal,oldVal) => {
      console.log('这是新值',newVal)
      console.log('这是旧值',oldVal)
    },{
      deep:true,
      immediate:true,
    })
************************************************************************
3,监听ref的数据
  let count = ref(1)
 watch(count, (newValue, oldValue) => {
    console.log(`count新值:${newValue}`, `count旧值:${oldValue}`)
  })

** 使用 computed 定义一个计算属性 rideCount,返回 count 之间的乘积**
  let rideCount = computed(() => {
    return count.value * count.value
  })
watch(rideCount, (newValue, oldValue) => {
    console.log(`rideCount新值:${newValue}`, `rideCount旧值:${oldValue}`)
  })

************************************************************************
4,侦听reactive声明的响应式对象
  let person = reactive({
    name: 'Echo',
    address: {
      city: 'GuangZhou'
    }
  })
 watch(person, (newValue, oldValue) => {
    console.log(newValue, oldValue)
  })
 使用 watch 函数侦听 name 属性的变化
  watch(
    () => person.name,
    (newValue, oldValue) => {
      console.log(`新name:${newValue}`, `旧name:${oldValue}`)
    }
  )
************************************************************************
5.监听多个数据变化
 const count = ref(0);
    const obj = reactive({
      name:'zs',
      age:14
    });
    const changeName = () => {
      obj.name = 'ls';
    };
    watch([count,obj],() => {
      console.log('监听的多个数据改变了')
    })



上一篇 下一篇

猜你喜欢

热点阅读