vue中如何监听data中的json格式的数据

一、 应用场景

在开发vue项目中,当你想监听一个student对象中的学生姓名时,该怎么实现实时监听呢

student: {
  name: '张三',
  id: '1001',
  age: 12
}

二、启用深度监听

在这里开启deep: true代表对这个json对象启动了深度监听

watch: {
    student:{
        deep:true,
        handler(newVal,oldVal){
            console.log('newValue', newVal);
            console.log('oldValue', oldVal);
        }
    }
}
注意: 虽然这样的深度监听能够监听到数据变化了,但是不能监听到数据的值时怎样变化的,输出打印的结果也都是一样的

三、watch + computed 结合使用

1. 在computed计算属性中去监听并返回Student.name的值到newStudentName

2. 在watch监听到newStudentName的变化后,对变化前后的值进行操作

computed: {
     newStudentName: function() {
         return this.student.name
     }
},
watch: {
     newStudentName(newValue, oldValue) {
         console.log('newValue', newValue);
         console.log('oldValue', oldValue);
     }
 },

display: flex;
justify-content: center;

你可能感兴趣的:(vue中如何监听data中的json格式的数据)