vue监听某个对象属性变化

<template>
  <div class="test">
    <div class="row">
      <input type="text" v-model="student.name" />
      <input type="text" v-model="student.age" />
      <input type="text" v-model="student.sex" />
      <input type="text" v-model="student.height" />
      <input type="text" v-model="student.address" />
    </div>
    <div class="row">
      <span class="but" @click="add">add响应式</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      student: {
        age: 23,
        name: "梧桐芊羽",
        sex: "男",
        height: 178
      },
      weather: "晴天"
    };
  },

  methods: {
    /**
     * 若直接给某个对象添加属性是不会触发响应式的,若要新增属性变为响应式的如下所示
     * this.$set(相应对象, 对象属性名, 对象属性值);
     */
    add() {
      this.$set(this.student, "address", "九天行哥欠");
      console.log(this.student);
    }
  },

  watch: {
    /**
     * 普通watch无法监听到对象内部属性变化,只有data中数据改变时才能监听变化。因此可添加deep属性:深层遍历,会监听student对象所有属性都变化。
     *
     * **/
    student: {
      handler(newValue, oldValue) {
        console.log("对象所有属性监听", newValue, oldValue);
      },
      deep: true
    },

    //由于上一种监听每次对象属性变化都会导致handler执行,若只想监听对象中某个属性变化,如下所示
    "student.name": {
      handler(newValue, oldValue) {
        console.log("单个属性监听", newValue, oldValue);
      }
    },

    /**
     * vue中watch首次加载时不会调用的,只有值变化时才能执行,若要首次调用,需要使用immediate属性。请使用如下方法
     * https://www.cnblogs.com/shiningly/p/9471067.html
     */
    weather: {
      immediate: true, //true首次加载执行,否则不执行为false或不添加此属性
      handler(newValue, oldValue) {
        console.log("首次触发", newValue, oldValue);
      }
    }
  },
  //计算属性监听某个值的变化
  computed: {
    studentName() {
      return this.student.name;
    }
  }
};
</script>

<style>
</style>


在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ee_11eeeeee/article/details/108216672