为什么更改 beforeCreated/created/beforeMount 中的数据不能在

为什么更改 beforeCreated/created/beforeMount 中的数据不能在 VUE 中触发 watch?


<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


红颜莎娜
浏览 395回答 1
1回答

蛊毒传说

这与我预期的一样。如果考虑下面的生命周期序列,对父母的子组件只得到创建后&nbsp;beforeMount父和之前mounted的父母。所以,对孩子你的手表是不会火变化中所作的道具beforeCreate或created由家长,因为孩子没有在这一点上存在。家长&nbsp;beforeCreate家长&nbsp;created家长&nbsp;beforeMount如果&nbsp;immediate: true传递了初始值,则子观察者将在此处触发孩子&nbsp;beforeCreate孩子&nbsp;created孩子&nbsp;beforeMount孩子&nbsp;mounted此处对属性的任何更改都将从此时触发子观察者家长&nbsp;mounted在您的观察者中,您immediate: false在手表上设置值。这意味着,当设置属性的初始值时,它不会触发。如果将其更改为 true,您会看到父级设置的值beforeMount会在创建子组件时立即触发监视。此外,如果您在父mounted生命周期钩子中再次更改值,则无论immediate.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript