Learn about Lifecycle Hooks in Vuejs

Tram Ho

Lifecycle hooks: lets you know when component is create , add to the DOM , updated , destroyed .

Here’s an image from the Vue.js documentation that shows the life cycle of a Vue Instance .

I will divide 4 common pairs of Hooks for you to remember more easily:

  1. beforeCreate vs created
  2. beforeMount vs mounted
  3. beforeUpdate vs updated
  4. beforeDestroy vs destroyed

Or let’s go through each pair of Hooks and examples to understand how it works.

1. beforeCreate vs created

  • beforeCreate :
    • run before render
    • is called synchronously right after the instance has been initialized
    • data and methods not instantiated so they cannot be obtained at this stage.

Result:


  • created :
    • run before render
    • Run after the beforeCreate finishes running.
    • data created data and methods can be obtained at this stage.
    • $el (the root DOM element that the Vue instance is managing) does not yet exist because it is not mounted yet

Result:

2. beforeMount vs mounted

  • beforeMount
    • Run after created run
    • Prepare for mounting
  • mounted
    • Run after the mounting has ended.
    • $el : This guy in created cannot get it, but if he is mounted , he has the same result as shown.
    • Note: At this stage, all components are not mounted . If you want to wait until everything is render then you can learn more about the guy vm. $ NextTick in mounted .

For example:

Result:

3. beforeUpdate vs updated

Returning to the image above, we can see that when there is the data change, this Hook pair will run:

  • beforeUpdate
    • Call when the data changes and before the DOM is patch .
    • Get old DOM data before changing to new DOM
  • updated
    • Called after data changes cause the DOM to be re-render and patch .
    • Limit change data on this Hook, instead use a computed or watcher instead.
    • Like mounted : in this stage all components will not be re-render . If you want to wait for everything to re-render then you can learn more about vm. $ NextTick in updated

Example: Create a text and a button, after the first render, click on the button

Result:

4. beforeDestroy vs destroyed

  • beforeDestroy : Called before the instance is destroy . At this stage, the instance is still fully functional.
  • destroyed : Called after the instance has been destroy . When this hooks are called, all directives of the instance are unbound , all event listerner are removed , and all children of the instance are destroy .

Example:

Result: when the button is clicked

Hopefully after reading this article, based on the basic concepts, you can be more creative and flexible on your own while doing your project.

If you do not understand or have suggestions for the article, please leave a comment [email protected] # $% ^ & *

Share the news now

Source : Viblo