Demystifying Vue Lifecycle Methods

Chris Nwamba
👁️ 3,267 views
💬 comments

Using components in your application is one thing but understanding how they work and knowing their lifecycle (when they are created, added to your DOM, updated or destroyed) is very important. You can hook into each of these component lifecycle methods to perform specific application tasks. In this post, I will explain the various lifecycle methods in Vue and how they work as well as when they should be implemented.

What are Lifecycle methods?

Lifecycle methods serve as a viewpoint into how our built components work behind the scenes. They provide you with methods that enable you trigger different actions at different junctures of a component’s lifecycle. They also auto-bind to your component so that you can use the component’s state and methods. Actions of lifecycle methods can be broken down into four categories:

  • Creation
  • Mounting
  • Updating
  • Destruction

Creation

Creation methods are used to perform actions on your component before adding it to the DOM. They should be used when configuring your component during both client as well as server side rendering. Creation methods are implemented using beforeCreate() and created() hooks.

beforeCreate(): The beforeCreate() hook observes data and initialization events in your component. Here, data is still not reactive and events that occur during the component’s lifecycle have not been set up yet. Check out the example below:

  new Vue({
    data: {
     x: 5
    },
    beforeCreate: function () {
      // `this` points to the view model instance
      console.log('x is: ' + this.x)
    }
  })
     // x is: undefined

created(): The created() hook is invoked when Vue has set up events and data observation. Here, events are active and access to reactive data is enabled though templates have not yet been mounted or rendered. Check out the code block below:

  new Vue({
    data: {
     x: 5
    },
    created: function () {
      // `this` points to the view model instance
      console.log('x is: ' + this.x)
    }
  })
     // x is: 5

Mounting

The most used methods when working with components, mounting methods let you access your component immediately before and after it is rendered the first time. They should be used if the DOM of your component needs to be modified immediately before or after it is initially rendered.

As mounting hooks do not run during server side rendering, they shouldn’t be used for fetching data for components on initialization. created() methods are best suited for that purpose.

beforeMount(): The beforeMount() method is invoked after our template has been compiled and our virtual DOM updated by Vue. After this, the $el property is added to the Vue instance, the native DOM is updated and the mounted() method is invoked.

  new Vue({
    beforeMount: function () {
      // `this` points to the view model instance
      console.log(`this.$el is yet to be created`)
    }
  })

mounted(): The mounted() method gives you access to templates and enables interaction with the DOM. It is mostly used for fetching data for your component and modifying the DOM to integrate other libraries and frameworks asides Vue. Let’s take a look at the code block below:

<div>
    <p>I'm text inside the component.</p>
</div>

Using the mounted() method to fetch this data from the DOM:

  new Vue({
    el: '#app',
    mounted: function() {
      console.log(this.$el.textContent) 
    }
  })
  // I'm text inside the component.

Created vs Mounted

Updating

Updating methods are useful for debugging. They are called whenever a reactive property used by your component changes or re-renders. The component’s DOM would have been updated when this hook is called so you can use updating methods to perform DOM dependent operations. It’s advised you don’t use updating methods to change state, computed properties or watchers are best fit for that instead.

beforeUpdate(): This method runs after data changes on your component and the update cycle begins right before the DOM is patched and re-rendered. It allows you get the new state of any reactive data on your component before it is rendered. Check out the code block below:

<div>
  <p>{{counter}}</p>
</div>

Interaction with our Vue instance:

  new Vue({
    el: '#app',
    data() {
      return {
        counter: 0
      }
    },
     created: function() {
      setInterval(() =&gt; {
        this.counter++
      }, 1000)
    },

    beforeUpdate: function() {
      console.log(this.counter) // Logs the counter value every second, before the DOM updates.
    }
  })

updated(): The updated() method runs after data changes on your component and the DOM re-renders. Take a look at the example below:

<div>
  <p>{{counter}}</p>
</div>

Interacting with our Vue instance gives:

  new Vue({
    el: '#app',
    data() {
      return {
        counter: 0
      }
    },
     created: function() {
      setInterval(() =&gt; {
        this.counter++
      }, 1000)
    },
    updated: function() {
      console.log(+this.$refs['dom'].textContent === this.counter) // Logs true every second
    }
  })

Destruction

Destruction methods are used in the final moments of a component’s lifecycle. They allow you perform actions such as cleanup when your component is destroyed and are executed when your component is torn down and removed from the DOM.

beforeDestroy(): This method is executed right before your component is destroyed. Here your component is still fully present and functional. If you need to cleanup events, beforeDestroy() is the best time to do that. Check out the code block below:

new Vue ({
  data() {
    return {
      coolMethods: 'Lifecycle methods are awesome!'
    }
  },

  beforeDestroy: function() {
    // Perform the teardown procedure for coolMethods which in this case is nothing.
    this.coolMethods = null
    delete this.coolMethods
  }
})

destroyed(): This method is called after your component has been destroyed, its directives have been unbound and its event listeners have been removed. The destroyed() method can be used to do any last minute cleanup or informing a remote server that the component was destroyed. Check out the example below:

  import destructionUpdateBot from './destruction-site'
  new Vue ({
    destroyed: function() {
      console.log(this) // Nothing to show here
      destructionUpdateBot.bomb('Target acquired.')
    }
  })

Summary

That’s it. That’s all Vue lifecycle methods are and nothing more. Now you should be able to visualize the journey of a Vue instance whenever it is initialized and as well customize you own code using these various hooks or methods should the need arise. You can always look up Vue’s documentation for other methods and properties to use alongside lifecycle methods when creating your components.

Chris Nwamba

49 posts

JavaScript Preacher. Building the web with the JS community.