Sign in
Log inSign up
Vuejs Lifecycle Hooks

Vuejs Lifecycle Hooks

Sunil Joshi's photo
Sunil Joshi
·Jul 31, 2020·

6 min read

In this tutorial you will learn and gain understanding of Vue.js lifecycle Hooks. you will also gain in-depth understanding of how components are created and destroyed behind the scenes.

Lifecycle hooks are the entry point to virtually all front-end frameworks out there, having a good understanding of when your components are created, mounted, updated and destroyed is essential to understanding the library reactivity.

Understanding Lifecycle Hooks in Vue.js is fairly easy. The diagram below is an illustration of a full lifecycle of a Vue.js component.

vue-cycle.jpg

Watch how the lifecycle hooks are changing at different stages of the vue templates compilation.

According to Vue.js documentation each Vue instance goes through a series of initialization steps when it’s 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. Along the way, it also runs functions called lifecycle hooks, giving users the opportunity to add their own code at specific stages.

Vue Created Hooks

BeforeCreate Hook

The beforeCreated hook is the first hook on the initialisation stage, it is triggered before the instance is created, hence the reactivity is not set up on at this state. This means that we you can’t access or update data. If had data coming from your back-end API, calling it within the beforeCreated hook will return undefined. See Example.

<script>
  export default {
    beforeCreated(){
      console.log(data);
      //This will return undefined 
    }
  }
</script>

Created Hook

The created hook is triggered when the component is created, here we have access to the component’s data and reactivity is created. However, templates and virtual DOM are not yet mounted within this hook. See Example below:

<script>
  export default {
    data(){
      return{
        message: "I am learning Vue lifecycle hooks"
      }
    },

    computed:{
      messageChange(){
        console.log(`This will look up to ${this.message} for changes`);
        return this.messages 
      }
    },

    created(){
      this.message = "now the message is changed";
      console.log(`messageChange will be updated since reactivity is present`);
    }
  }
</script>

Vue Mounted Hooks

BeforeMount Hook

The beforeMount hook is triggered before the initial render of the Virtual DOM and compilation of template or render functions. Use of this hook during server-side rendering is not recommended it can’t be called after render. See Example:

<script>
  export default {
    beforeMount(){
      console.log(`${this.el} is about to be mount`);
    }
</script>

Mounted Hook

The mounted hook full reactivity is established, templates, and rendered DOM (via. this.$el).

The mounted hook is reported to be the most used lifecycle hook. Most people use it for fetching data for their component (I recommend using Created Hook). See example:

<template>
  <p>Text inside a component</p>
</template>

<script>
  export default {
    mounted(){
      console.log(this.$el.textContent);
      //This will return the text from the template 
    }
</script>

Vue Updating Hooks

Updating hooks are triggered whenever a reactive property used by your component changes, or through user input causes it to re-render. They updating hooks allow you to hook into the watch-compute-render cycle for your component.

You can use it if you want to know when you component re-renders. To target the state of a reactive component please computed property or watchers instead.

BeforeUpdate Hook

The beforeUpdate Hook is triggered before a component is re-rendered, it is initiated when data changes in a component. This is a good place to track the state of a reactive component before it is rendered. See Example:

<script>
  export default {
    data(){
      n: 1,
    },

    beforeUpdate(){
      console.log(this.n) //sets the value of n to 300 after 1,500 seconds;
    },

    created(){
      setTimeOut(() => {
        this.n = 300
      }, 1500);
    }
</script>

Updated Hook

The updated hook is called after a data change causes the virtual DOM to be re-rendered and patched. The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a computed property or watcher instead.

<template>
  <p ref="dom-element">{{name}}</p>
</template>

<script>
export default {
  data() {
    return {
      name: "Emmanuel Etukudo"
    }
  },

  updated() {
    // Track update on the DOM element.
    console.log(this.$refs['dom-element'].textContent === this.name)
  },

  created() {
    setTimeout(() => {
      this.name = "John Doe"
    }, 1000)
  }
}
</script>

Destruction Hooks

Destruction hooks are used to perform actions when your components are destroyed, such as remove component-based events. They when components are removed from the DOM.

BeforeDestroy Hook The beforeDestroy hook is triggered before a Vue instance is destroyed. At this stage the instance is still fully functional.

<script>
export default {
  data() {
    return {
      accessToken: localStorage.getItem('accessToken'),
    }
  },


  beforeDestroy() {
    // Remove the token.
    localStorage.removeItem('accessToken');
  },  
}
</script>

Destroyed Hook

The destroyedHook is triggered after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.

<script>
export default {
  destroyed() {
    console.log(this) // Nothing is left to log
  }
}
</script>

There are two other hooks that are not captured in this article there are keep-alive hooks the Activate & Deactivated. You can look them up on Vue documentation website. Thank you for reading, drop your comments I will like to read from you.