Instance Lifecycle


Instance Lifecycle hooks

Each Vue instance goes through a series of initialization steps after it's been created.  For example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. These series of initialization steps are called the "Instance Lifecycle". We can hook into the lifecycle steps using a few properties:

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

In all my Vue projects, I've only used two out of above list; so for the sake of keeping this tutorial simple those are the only ones I review in this chapter. 

In case you would like to get into more details on the instance lifecycle take a look at the Vue Lifecycle Diagram.


created

The Vue instance has just been created. 

Some actions need to take action since the beginning of our Vue application. The created hook is where those codes need to be. For example when we need to fetch some basic data via ajax. Since we haven't reviewed ajax calls in Vue yet, I'm gonna write a simpler example:

new Vue({
el: '#app',
created() {
console.log('The application has started');
}
});

Above code logs "The application has started" right after running the application. 

It is recommended (cleaner) to only call methods inside the created() hook. So let's refactor above code to:

new Vue({
el: '#app',
created() {
this.logAppHasStarted();
},
methods: {
logAppHasStarted() {
console.log('The application has started');
}
}
});

In this example the logAppHasStarted() contains only one line of code, so this refactoring might seem overdoing. But I suggest you stick to it, because in real life applications there's going to be more than one line of code, and you'll want to keep your code clean and easy to read. 


mounted

Not only the instance has been created, but it's been bound to the DOM. Or as you may say it, it's been mounted to the DOM. 

When do we need the mounted hook? When we need to select a DOM element(Because we can't select something that hasn't been created it yet). 

There is a big chance you won't be needing the mounted hook in your Vue application(because you already got the "created" hook); except when you're using jQuery plugins in your app. If that's the case and you've been told you need to run some code inside below classic jQuery code:

$( document ).ready(function() {
/* some code to get the jQuery plugin working */
});

The Vue way:

The created hook might not be enough. That's because the created hook doesn't guarantee the existence of the DOM. Just place your code inside the mounted and the $nextTick:

mounted() {
this.$nextTick(function() {
/* some code to get the jQuery plugin working */
})
}

Above code guarantees the existence of the DOM.  

Still not sure about above code? Worry not! Just move on to the next chapter. Once you need above code, you'll know it. 


Comments: