Render a child component only after async method is completed in parent's mounted

Viewed 1634

I have a parent component which renders a child component. I am making an async call (an axios 'get' request from Vuex actions) from inside the mounted of the parent component, which fetches the data required for the child component.

I want to prevent the rendering of the child component til that async call is completed. Can someone suggest some elegant approach?

1 Answers

v-if

<child v-if="mydata" />

mydata can be a data property initialized to null:

data() {
  return {
    mydata: null
  }
}

When that's populated in created/mounted, the child component will show.

async created() {
  const response = await axios // ...
  this.mydata = response.data;
}

EDIT: Based on your comments below. For Vuex, do this instead:

  • Continue using the v-if

  • Use a computed instead of a data property:

computed: {
   mydata() {
     return this.$store.state.mydata;
   }
}

alternate syntax using mapState

import { mapState } from 'vuex';

computed: {
   ...mapState(['mydata'])
}
Related