Vueにおける親子コンポーネントのライフサイクル関数の実行タイミング

1771 ワード

問題の背景:
サブコンポーネント内のmountedでは、親コンポーネントから送信されるprops属性値が取得できないことがよくあります.
ライフサイクル関数の実行順序:
親beforeCreated->親created->親beforeMount->子beforeCreate->子created->子beforeMount->子mounted->親mounted
//    


import TC from './TC'
export default {
  data () {
    return {
      pName: 'this is parent'
    }
  },
  components: {
    'tc': TC
  },
  beforeCreate () {
    console.log('parent beforeCreate')
  },
  created () {
    console.log('parent created')
  },
  beforeMount () {
    console.log('parent beforeMount')
  },
  mounted () {
    console.log('parent mounted')
    this.pName = 'this is not parent'
  }
}


//    


export default {
  props: ['cName', 'pName'],
  watch: {
    pName: {
      immediate: true,
      handler: function () {
        console.log('watch pName', this.pName)
      }
    }
  },
  beforeCreate () {
    console.log('child beforeCreate')
  },
  created () {
    console.log('child created')
  },
  beforeMount () {
    console.log('child beforeMount')
  },
  mounted () {
    console.log('cName', this.cName)
    console.log('pName', this.pName)
    console.log('child mounted')
  }
}


/**     :
parent beforeCreate
parent created
parent beforeMount
child beforeCreate
watch pName this is parent
child created
child beforeMount
cName this is child
pName this is parent
child mounted
parent mounted
watch pName this is not parent */

親コンポーネントmountedでpName値を変更すると、親コンポーネントmountedの実行が子コンポーネントmountedの後になるため、子コンポーネントmountedでは変更後の値を取得できません.