监视属性watch

监视属性watch

  • 与Vue2.x中watch配置功能一致

  • 两个小“坑”:

    • 监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。

    • 监视reactive定义的响应式数据中某个属性时:deep配置有效。

<template>
  <div class="about">
      <h1>监视属性</h1>
      <div>第一种:</div>
      数字 : {{num}}
      <button @click="num++">数字+1</button> <hr>
      姓名 : {{name}}
      <button @click="name+=1">改名姓名</button> <hr>
      <div>第三种情况 : 监视不到oldValue的值</div>
      <input type="text" v-model="phone.name1"> <br>
      <input type="text" v-model="phone.name2"> <br>
      <input type="text" v-model="phone.a.b.c">
  </div>
</template>
<script>
import { reactive, ref ,computed,watch } from 'vue'
export default {
  setup(){
    let num = ref(1)
    let name = ref('吴宇腾')
    // 第一种情况 : 使用ref的监视一个数据 
    watch(num,(newValue,oldValue)=>{
      console.log(newValue,oldValue)
    })

    watch(name,(newValue,oldValue)=>{
      console.log(newValue,oldValue)
    })

    // 第二种情况 : 使用ref的监视多个数据
    watch([num,name],(newValue,oldValue)=>{
      console.log('使用ref的监视多个数据')
      console.log(newValue,oldValue)
    })

    
    let phone = reactive({
        name1 : '小米',
        name2 : '红米',
        a:{
          b:{
            c:111
          }
        }
    })
    

    // 第三种情况 : 监视reactive定义的响应式数据,监视不到oldValue的值(深度的属性也是得不到),默认开启了深度监视
    watch(phone,(newValue,oldValue)=>{
      console.log('使用reactive的监视')
      console.log(newValue,oldValue)
    })

    // 第四种情况 : 使用reactive监视,要监视对象的某一个值,可以得到oldValue的值
    watch(()=>phone.name1,(newValue,oldValue)=>{
      console.log('使用reactive监视,要监视对象的某一个值')
      console.log(newValue,oldValue)
    })  

    // 第五种情况 : 使用reactive监视,要监视对象的某一个值的深度属性,需要开启深度监视,但是得不到oldValue的值)
    watch(()=>phone.a,(newValue,oldValue)=>{
      console.log('使用reactive监视,要监视对象的某一个值的深度属性')
      console.log(newValue.b.c,oldValue.b.c)
    },{deep:true})   
    
    // 第六种情况 : 使用reactive监视,要监视对象的多值,可以得到oldValue的值
    watch([()=>phone.name1,()=>phone.name2],(newValue,oldValue)=>{
      console.log('使用reactive监视,要监视对象的某一个值')
      console.log(newValue,oldValue)
    })  

    // 第七种情况 : 使用reactive监视,要监视对象的多值(其中一个是深度的属性),正常的可以得到oldValue的值,深度的不行
    watch([()=>phone.name1,()=>phone.a],(newValue,oldValue)=>{
      console.log('使用reactive监视,要监视对象的某一个值')
      console.log(newValue,oldValue)
    })

    return {num,name,phone}
  }
}
</script>

 

posted @ 2022-05-17 14:20  杨建鑫  阅读(58)  评论(0编辑  收藏  举报