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

时间:2019-11-22 09:28:32

标签: javascript vue.js

为什么更改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>

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

1 个答案:

答案 0 :(得分:2)

这符合我的预期。如果您考虑以下生命周期顺序,则在父级上,子级组件仅在父级上{em> beforeMount之后,在父级mounted之前创建。因此,您对孩子的监视不会因为父母在beforeCreatecreated中所做的道具更改而被解雇,因为此时孩子不存在。

  • 父母beforeCreate
  • 父母created
  • 父母beforeMount
    • 孩子beforeCreate
      • 儿童观察者将在 if immediate: true处触发,并传递初始值
    • 孩子created
    • 孩子beforeMount
    • 孩子mounted
  • 对此处属性的任何更改都会从此时触发孩子观察者
  • 父母mounted

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