问题:父组件在挂载后,通过http请求,得到数据后通过prop传递给子组件,但是子组件不显示内容。
分析下原因:
这个必定是生命周期这块的问题。
罗列下组件加载时,生命周期的排序:
1.开始加载
- 父组件beforeCreate
- 父组件created
- 父组件beforeMount
- 子组件beforeCreate
- 子组件created
- 子组件beforeMount
- 子组件mounted
- 父组件mounted
2.加载后,如果要更新数据,重新渲染的情况下
- 父组件beforeUpdate
- 子组件beforeUpdate
- 子组件updated
- 父组件updated
3.组件卸载销毁的时候
- 父组件beforeUnmount
- 子组件beforeUnmount
- 子组件unmounted
- 父组件unmounted
综上说看:
数据渲染过程可知子组件的mounted是先于父组件的mounted,所以获取不到异步请求后获取到的数据
开始解决问题
1.v-if解决
<MainReport v-if="content.length>0" :title="title" :content="content" >
</MainReport>
当获取到的content的值后,在渲染子组件。写法简单,也不用涉及到子组件的改造。
2.使用watch对父组件传递过来的数据进行监控
watch: {
content(newVal, oleVal){
console.log("content 发生变化")
console.log(newVal)
console.log(oleVal)
},
},
这样也可以监听到数据的变化,然后在改变后,重新赋值,也可以解决问题。但是要在子组件中修改。