vue 对象属性的监听

 

1.普通的监听

data() {
    return {
        msg: ''    
    }
},
watch: {
    msg(newValue, oldValue) {
        console.log(newValue)
    }
}

 

2.对象属性的监听:可以通过配置 deep 为true实现。直接监听整个属性,消耗大

data() {
  return {
    branch: {
      code: '3010100',
      name: '上海分公司'
    }   
    }
},
watch: {
  branch: {
    handler(newValue, oldValue) {
      console.log(newValue)
    },
    deep: true
  }
}

 

 3.对象具体属性的监听:可以结合计算属性的方法实现

data() {
  return {
    branch: {
      code: '3010100',
      name: '上海分公司'
    }   
    }
},
computed: {
  name() {
    return this.branch.name
  }
},
watch: {
  name(newValue, oldValue) {
    console.log(newValue)
  }
}

 

对象具体属性的watch可以直接用引号把属性括起来,就可以实现对象中特定属性的监听事件:

data() {
  return {
    branch: {
      code: '3010100',
      name: '上海分公司'
    }   
    }
},
watch: {
  'branch.name'(newValue, oldValue) {
    console.log(newValue)
  }
}

 

posted @ 2021-09-29 11:03  Fourteen  阅读(3132)  评论(0编辑  收藏  举报