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@2/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?
- Need just to trigger a call as soon as possible?
- Use
beforeCreate() - Why?
- It runs sooner than any of those hooks, but…
- Use
- Need to read from or modify
dataright away?- Use
created() - Why?
- State is only initialized between
beforeCreate()andcreated(), so if you assign some data beforecreated(), it would be lost.
- State is only initialized between
- Use
- Need anything that is generated after
created()?- Use
beforeMount() - Why?
- I don’t know anything that isn’t available at
created()and is available atbeforeMount()other than the compiledthis.$options.renderrender function (see source as well), so this case must really be a rare situation.
- I don’t know anything that isn’t available at
- Use