在寫vue項目的時候,父組件調用ajax的接口獲得數據,然后賦值給data中的初始值,然后通過props傳給子組件,子組件在created的時候,獲得的props的值有的時候是undefined,因為ajax是異步請求,執行的http線程,js線程執行的過程可能還沒有值的返回.
保證在子組件created的時候也有值,解決方案是在父組件中調用子組件的時候寫一個v-if,在ajax值返回的時候再v-if=‘true’解決
//父組件中
<v-child :data='data' v-if='flag'></v-child>
methods:{
init(){
this.axios.get().then((res)=>{
this.data=res.data;
this.flag=true
})
}
}
//子組件
props {
data: {
type: Object,
default: function () {
return { message: 'hello' }
}
}
}
created(){
this.init()
}
