Vue中父子组件的生命周期函数的执行时机

问题背景:

在子组件中mounted时经常发现无法获取到父组件传入的props属性值。

生命周期函数执行顺序:

父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted

// 父组件
<template>
  <div>
      <p>Test - Parent</p>
      <tc c-name="this is child" :p-name="pName"></tc>
  </div>
</template>
<script>
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'
  }
}
</script>

// 子组件
<template>
  <div>
    <p>Test - Child</p>
  </div>
</template>
<script>
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')
  }
}
</script>

/** 运行结果:
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之后。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值