likwidmonster
likwidmonster

Reputation: 413

Vue 2 load ajax data before component render

I have a few nested Vue Components and the child loads the data using an AJAX call. Is it possible to have the parent wait to finish mounting until the child has made the ajax call and finished rendering? I have seen some solutions that use async created() or beforeRouteEnter: function (to, from, next) but I cannot seem to get it to work on the Fiddle.

I have a jsfiddle posted here: https://jsfiddle.net/likwidmonster/20potzwc/16/

In the jsfiddle, I have nextTick functions that print to the log when each is loaded. I would like it to have the following output:

grandchild next tick
child next tick
grandchild next tick
child next tick
grandchild next tick
child next tick
parent next tick

Upvotes: 0

Views: 1988

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50798

You cannot stop the parent from loading so to speak, but you can make it seem like it is by applying v-cloak, v-if, or v-show to the top level HTML element in the template. You can have a property on the parent, such as:

loaded: false

You can then use sync to synchronize this value with the parent and child, by attaching it to the child like this:

<child :loaded.sync="loaded"></child>

Then, within the child, you can use $emit when your Promise resolves:

this.$emit('update:loaded', true)

Which will tell the parent to change loaded from false to true.

Finally, you can make sure the parent isn't rendering until that variable is try by attaching a v-show directive which and passing it the loaded variable:

<div v-show="loaded">

So on initial page load this is false. When the data is finished loading and the child $emit's, then it will be true, and the parent will become visible.

Upvotes: 1

Related Questions