美文网首页
vue3 watch

vue3 watch

作者: 糖醋里脊120625 | 来源:发表于2024-01-03 10:56 被阅读0次
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('监听的多个数据改变了')
    })



相关文章

网友评论

      本文标题:vue3 watch

      本文链接:https://www.haomeiwen.com/subject/mtgmndtx.html