• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

学习Vue3 第十章认识watch侦听器

武飞扬头像
小满zs
帮助1

watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用

watch第一个参数监听源

watch第二个参数回调函数cb(newVal,oldVal)

watch第三个参数一个options配置项是一个对象{

immediate:true //是否立即调用一次

deep:true //是否开启深度监听

}

监听Ref 案例

  1.  
    import { ref, watch } from 'vue'
  2.  
     
  3.  
    let message = ref({
  4.  
    nav:{
  5.  
    bar:{
  6.  
    name:""
  7.  
    }
  8.  
    }
  9.  
    })
  10.  
     
  11.  
     
  12.  
    watch(message, (newVal, oldVal) => {
  13.  
    console.log('新的值----', newVal);
  14.  
    console.log('旧的值----', oldVal);
  15.  
    },{
  16.  
    immediate:true,
  17.  
    deep:true
  18.  
    })
学新通

监听多个ref 注意变成数组啦

  1.  
    import { ref, watch ,reactive} from 'vue'
  2.  
     
  3.  
    let message = ref('')
  4.  
    let message2 = ref('')
  5.  
     
  6.  
    watch([message,message2], (newVal, oldVal) => {
  7.  
    console.log('新的值----', newVal);
  8.  
    console.log('旧的值----', oldVal);
  9.  
    })

监听Reactive

使用reactive监听深层对象开启和不开启deep 效果一样

  1.  
    import { ref, watch ,reactive} from 'vue'
  2.  
     
  3.  
    let message = reactive({
  4.  
    nav:{
  5.  
    bar:{
  6.  
    name:""
  7.  
    }
  8.  
    }
  9.  
    })
  10.  
     
  11.  
     
  12.  
    watch(message, (newVal, oldVal) => {
  13.  
    console.log('新的值----', newVal);
  14.  
    console.log('旧的值----', oldVal);
  15.  
    })
学新通

案例2 监听reactive 单一值

  1.  
    import { ref, watch ,reactive} from 'vue'
  2.  
     
  3.  
    let message = reactive({
  4.  
    name:"",
  5.  
    name2:""
  6.  
    })
  7.  
     
  8.  
     
  9.  
    watch(()=>message.name, (newVal, oldVal) => {
  10.  
    console.log('新的值----', newVal);
  11.  
    console.log('旧的值----', oldVal);
  12.  
    })

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgheiif
系列文章
更多 icon
同类精品
更多 icon
继续加载