父子组件经过 props 传值,当所传值须要异步请求获取时,子组件在挂载完成阶段(mounted),拿不到props值javascript
父组件:vue
<template>
<div>
<son :father-data="fatherData"/>
</div>
</template>
<script>
import son from './son.vue'
export default {
name: "Father",
component: {
son
},
data: {
fatherData : {}
},
created() {
// 假设已经引入了 axios 组件,在这里发起异步请求
this.axios.get('http://some_api/data').then((res) => {
this.fatherData = res.data.data // 假设获取到的值为 "{ name: 'hehe'}}"
}).catch((err) => {
console.log(err.data.errmsg)
})
},
})
</script>
复制代码
子组件:java
<template>
<div>
<p>son component</p>
</div>
</template>
<script type="text/javascript">
export default {
name: "Son",
props: {
fatherData: {
type: Object,
default: () => {}
}
},
mounted() {
console.log(this.fatherData) // 输出结果为:{}
},
watch: {
fatherData(newV, oldV) {
console.log(newV) // 输出结果为: {name: 'hehe'}
}
}
})
</script>
复制代码
上面的代码,咱们从生命周期的角度,从头走一遍:ios
- 父组件开启生命周期
- 父组件进行到 created 阶段,完成 fatherData 的初始化,并发出了异步请求获取数据。
- 父组件进行到 beforeMount 阶段,发现有引用子组件,因而开始编译子组件
- 子组件开启生命周期
- 子组件进行到 created 阶段,完成 props 的初始化(其值为 fatherData的初始值 {})
- 子组件进行到 mounted 阶段,输出 props
- 父组件进行到 mounted 阶段
- 异步请求返回数据,并更新了 fatherData (忽略 beforeUdate 和 updated,不是重点)
- 子组件中 watch 检测到 fatherData 值变化,触发函数输出 {name: 'hehe'}
能够看出,有三个关键因素决定了这种结果:axios
子组件应增长 v-if 判断条件,在异步请求返回数据后进行编译渲染。api