watch 监听reactiv

<template>
  <div>
    本人 : {{reactiveWatch.name}} - {{reactiveWatch.age}}
    朋友 : {{reactiveWatch.firend.name}}
    同桌 : {{reactiveWatch.firend.hang.name1}} - {{reactiveWatch.firend.hang.name2}}

    <br><button @click="reactiveWatch.name = '吴宇腾1号' ,reactiveWatch.age++">修改本人</button>
    <br><button @click="reactiveWatch.firend.name = '林丽友'">修改朋友</button>
    <br><button @click="reactiveWatch.firend.hang.name1 = '小君'">修改同桌</button>
  </div>
</template>

<script>

import {reactive,watch} from 'vue'

export default {

  setup(){

    // 1.reactive的监听 - 默认都是深度监听
    const reactiveWatch = reactive({
      name:'吴宇腾',
      age:18,
      firend:{
        name:'小丽',
        hang:{
          name1:'小吴',
          name2:'小样'
        }
      }
    })

    // watch(reactiveWatch,(newV,oldV)=>{
    //   console.log(newV,oldV)
    // },{
    //   immediate:true
    // })

    // 想要取不是proxy的值 : 这样没有深度监视,需要加上
    watch(()=>({...reactiveWatch}),(newV,oldV)=>{
      console.log(newV,oldV)
      console.log(newV.name)
      console.log(newV.firend.name)
      console.log(newV.firend.hang.name1)
    },{
      // immediate:true
      deep:true
    })

    return {
      reactiveWatch
    }
  }
}
</script>

 

posted @ 2022-08-24 15:53  杨建鑫  阅读(28)  评论(0编辑  收藏  举报