1、vue中提供了在watch监听时设置deep:true 就可以实现对对象的深度监听

watch:{
  obj:{ //监听的对象
    deep:true, //深度监听设置为 true
    handler:function(newV,oldV){
      console.log('watch中:',newV)
    }
  }
}


例如:
data () {
    return {
      obj:{
        name:'夜空中最亮的星星',
        age:18
      }
    }
  },
  watch:{
    'obj.name':{
      deep:true,
      handler:function(newV,oldV){
        console.log('watch中:',newV)
      }
    }
  }
 

2、利用computed配合watch实现单个属性的深度监听

data () {
  return {
    obj:{
      name:'夜空中最亮的星星',
      age:18
    }
  }
},
computed:{
  name(){
    return this.obj.name;
  }
},
watch:{
  name(newV){
   console.log('watch中name为:',newV)
  }
}

 

posted on 2021-04-13 09:16  盐孩儿  阅读(2502)  评论(0编辑  收藏  举报