In this tutorial, you’ll learn how to trigger a function immediately after the route was loaded.
If you’re subscribed to my newsletter, you’ve already seen some examples, where I call a function as soon as page loads, e.g. here.
Instance lifecycle hooks in Vue.js
First of all, let’s quickly rehearse how Vue.js stages of initialisation work. As you know, Vue.js components have a series of lifecycles. They allow users to add stage-specific code.
What lifecycle hooks are
When you load a component it goes through a series of stages:
- beforeCreate()
- created()
- beforeMount()
- mounted()
- beforeUpdate()
- updated()
- beforeDestroy()
- destroyed()
As soon as you load a component, created()
hook is called. At this stage, component data()
is loaded as well as computed properties, watchers and methods.
Then your component is mounted()
to the DOM. It’s when your component gets inserted to the DOM.
How to use lifecycle hooks
To use lifecycle hooks you need to create a method on your component (use one of the hook names above).
new Vue({
el: "#app",
data: {
},
created() {
console.log('Component is created')
},
mounted() {
console.log('Component is mounted')
}
})
Component is mounted
will be printed in the console after component is created
.
In most cases both of these hooks can be used to call a function as soon as our page loads. Which one should you choose?
created() or mounted()
It’s safer to call a function is a mounted()
hook because our component is fully initialised and a DOM is fully loaded. That means you can access anything in your component.
However, if you want to fetch API data in your component I’d suggest doing it in the created()
hook. You don’t need a DOM for your API call. In addition, your data will be loaded slightly faster.
new Vue({
el: "#app",
data: {
},
computed: {
...mapGetters({
items: 'getItems'
})
},
created() {
this.$store.dispatch('LOAD_ITEMS')
}
})
Accessing the DOM using this.$el
As I mentioned earlier, computed()
hook doesn’t have access to the DOM. Whereas, mounted()
does have access.
created() {
console.log(this.$el)
},
mounted() {
console.log(this.$el)
}
If you run this in your component, you’ll see that in the created()
hook the output will be undefined. It’s because the DOM doesn’t exist yet when created()
hook is called.
However, console.log(this.$el)
in the mounted()
hook will render our component’s DOM element.
If you find this post useful, please let me know in the comments below and subscribe to my newsletter.
Cheers,
Renat Galyamov
Want to share this with your friends?
👉renatello.com/vue-js-call-function-on-page-load
PS: Make sure you check other Vue.js tutorials, e.g. how to do list rendering (looping) using v-for.