Vue JS 3 Component LifeCycle

In previous blog we learned about component state and props:

Vue3 Component

Every vue component goes through series of initialization steps. When vue application starts until it is destroyed it goes through series of lifecycle methods shown in green boxes as below:

There are four main events which are sub divided into before and after methods:

  • Creation: stage when components are being created
  • Mounting: stage when components are being mounted
  • Updates: stage when state changes within a component
  • Destruction: stage when component is being destroyed

Let's checkout all above methods in following code and then understand them one by one:

VueJs 3 LifeCycle Methods

In vuejs 3 things have changed a bit some life cycles are removed or combined.

Creating Phase

When vue component is in creation phase it goes through following two life cycle methods:

  • BeforeCreate
  • created

Above two lifecycle methods are replaced with setup function in vuejs 3. When component is created it calls setup method. This hook is useful if you want to fetch some api data and then assign this data to state.

Mounting Phase

When vue component is mounting it goes through following two life cycle hooks.

  • onBeforeMount
  • onMounted

onBeforeMount function is called before mounting begins. onMounted method is called when component is mounted.

Updating Phase

As we learned earlier component has state which are reactive objects. When state changes it goes through update phase and calls following two methods:

  1. onBeforeUpdate
  2. onUpdated

onBeforeUpdate is called before view is re-rendered. onUpdated is called when view is re-rendered. As we learned in our previous tutorial when component state data changes update phase begins.

Destruction Phase:

When component is being destroyed vue calls following two lifecycle methods:

  • onBeforeUnmount
  • onUnmounted

onBeforeUnmount is called before component is being destroyed. onUnmounted is called when component is destroyed.

Above methods are widely used methods. There are other methods as well which you can learn more using following vue js lifecycle documentation link:

Lifecycle Hooks