vue2,父子组件的生命周期顺序控制

246 阅读1分钟

我们知道,父子组件生命周期顺序:

父 beforeCreate
父 created
子 beforeCreate
子 created
子 mounted
父 mounted

假如现在我们有个需求,父组件fetch完数据后,子组件再fetch数据。
假如现在的代码是这样的:

// 父
async created(){
  this.$data.myApiData = await MyAPI();
}
// 子
created(){
  const data = this.$parent.$data.myApiData;
  if(!data) throw new Error('data error');
  MyAnotherAPI(data);
}

由于异步的原因,子组件的created会先执行,拿不到值。

解决

思路:拿到数据后再v-if显示出子组件。

// 父
<子 v-if="showSon"/>
async created(){
  this.$data.myApiData = await MyAPI();
  this.$data.showSon = true;
}