为什么 Vue 在两个反应性数据突变超级接近时只会更新一次?

Why Vue will update only once when two reactive data mutation super close?

请看这个最小的例子

export default {
  data() {
    return {
      name: "Amy",
      age: 18,
    };
  },
  computed: {
    combinedDataForWatching() {
      return {
        name: this.name,
        age: this.age,
      };
    },
  },
  watch: {
    combinedDataForWatching() {
      console.log("Triggered!");
    },
  },
  mounted() {
    setTimeout(() => {
      this.name = "Bob";
      this.age = 20;
    }, 1000);
  },
};

控制台只会记录"Triggered!"一次,为什么会这样?

以及Vue是如何判断本次批量更新的?

来自Vue guide on reactivity

In case you haven’t noticed yet, Vue performs DOM updates asynchronously. Whenever a data change is observed, it will open a queue and buffer all the data changes that happen in the same event loop. If the same watcher is triggered multiple times, it will be pushed into the queue only once. This buffered de-duplication is important in avoiding unnecessary calculations and DOM manipulations. Then, in the next event loop “tick”, Vue flushes the queue and performs the actual (already de-duped) work.

因此,这两个 watch 触发器更新都发生在同一个更新周期中,并被反应性系统“去重”到一个调用中。