How to mount the child components only after data has been loaded with Vue.js and JavaScript?

Sometimes, we want to mount the child components only after data has been loaded with Vue.js and JavaScript.

In this article, we’ll look at how to mount the child components only after data has been loaded with Vue.js and JavaScript.

How to mount the child components only after data has been loaded with Vue.js and JavaScript?

To mount the child components only after data has been loaded with Vue.js and JavaScript, we can use the v-if directive to check if the data is loaded before rendering the child component.

For instance, we write:

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id='app'>

</div>

to add the Vue script and app container.

Then we write:

const Foo = {
  template: `<p>{{index}}</p>`,
  props: ['index']
}

const v = new Vue({
  el: '#app',
  template: `
    <div v-if='arr'>
    	<foo :key='i' :index='i' v-for='i of arr' />
    </div>
  `,
  data: {
    arr: undefined
  },
  components: {
    Foo
  },
  mounted() {
    setTimeout(() => {
      this.arr = [1, 2, 3, 4, 5]
    }, 1000)
  }
})

to add v-if to the div to see if arr is defined before we use v-for to render the array entries.

In the mounted hook, we assign this.arr to an array in the setTimeout callback, so there’s a delay until arr is assigned to the array.

Therefore, we should see a delay before Foo is rendered.

Conclusion

To mount the child components only after data has been loaded with Vue.js, we can use the v-if directive to check if the data is loaded before rendering the child component.