I'd like to know how before I render a page, I want to send an async GET request to my server to retrieve data and populate the properties in data. I heard the best way to do this is to call the function that sends this request in one of the three lifecycle hooks Vue js offers that operate before the DOM is rendered. The three are beforeCreate()
, created()
, beforeMount()
. Which one must this request be called in ideally? And why?
TL;DR in the general (and safe) case, use
created()
.
Vue's initialization code is executed synchronously.
Technically, any ASYNChronous code you run in beforeCreate()
, created()
, beforeMount()
will only respond after all of those hooks finish. See demo:
new Vue({
el: '#app',
beforeCreate() {
setTimeout(() => { console.log('fastest asynchronous code ever') }, 0);
console.log('beforeCreate hook done');
},
created() {
console.log('created hook done');
},
beforeMount() {
console.log('beforeMount hook done');
},
mounted() {
console.log('mounted hook done');
}
})
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<div id="app">
Check the console.
</div>
In other words, if you make an Ajax call in beforeCreate()
, no matter how fast the API responds, the response will only be processed way later, way after the created()
has been executed.
What should guide your decision, then?
beforeCreate()
data
right away?
created()
created()
?
beforeMount()
created()
and is available at beforeMount()
other than the compiled this.$options.render
render function (see source as well), so this case must really be a rare situation.