问题背景:
在子组件中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之后。