为什么在之前创建/创建/之前挂载中更改数据无法触发 VUE 中的监视?



为什么在 beforeCreated/created/beforeMount 中更改数据无法在 VUE 中触发监视?

<template>
  <div>
    <titi :namer="parentName"></titi>
  </div>
</template>
<script>
export default {
  components: {
    titi: {
      template: "<h1>{{namer}}</h1>",
      props: ["namer"],
      watch: {
        namer: {
          immediate: false,
          handler(val, oldVal) {
            console.log("jackieyin", val);
          }
        }
      },
      mounted() {
        console.log("jackieyin", "mounted");
      }
    }
  },
  data: function() {
    return {
      parentName: "jackieyin"
    };
  },
  beforeCreate() {
    console.log(222);
    this.parentName = "sunwukong";
  },
  created() {
    this.parentName = "kewu";
  },
  beforeMount() {
    this.parentName = "tangseng";
  },
  mounted() {
    // var that = this;
    // this.parentName = "tyty";
    // setTimeout(() => {
    //   that.parentName = "shaseng";
    // }, 500);
  }
};
</script>

我尝试在这些生命周期中更改数据,但无法触发子元素 props 手表。你可以在这里尝试: https://codesandbox.io/s/vue-watch-inx4z

这表现得像我所期望的那样。如果您考虑下面的生命周期顺序,则在父组件上,子组件仅在父组件beforeMount之后和父组件mounted之前创建。因此,您在孩子身上的手表不会因父母在beforeCreatecreated中对道具所做的更改而触发,因为那时孩子不存在。

  • beforeCreate
  • created
  • beforeMount
    • 儿童beforeCreate
      • 如果immediate: true观察程序将在此处触发,并传递初始值
    • 儿童created
    • 儿童beforeMount
    • 儿童mounted
  • 此处对属性的任何更改都将从此解雇儿童观察者
  • mounted

在观察程序中,设置immediate: false监视的值。这意味着,当设置属性的初始值时,它不会触发。如果将其更改为 true,您将看到父组件在中创建子组件时立即触发监视beforeMount设置的值。此外,如果您在父mounted生命周期挂钩中再次更改了该值,则无论 immediate 的值如何,子项中的观察程序都会选取该值。

最新更新