Lifecycle Hooks of Vue

Lifecycle hooks

Lifecycle hooks are a window to determine how the library works behind the scenes. Lifecycle hooks allow you to know when your component is created, added to the DOM, update or destroy.

What is Vue.js?

Vue.js is an open-source model–view–ViewModel front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You and is maintained by him and the rest of the active core team members coming from various companies such as Netlify and Netguru.

Vue core team plus contributions from over 230 open source community lovers. Vue is used by more than 870000 people.

It consists of an approachable core library that focuses on the view layer only, an ecosystem of supporting libraries that helps you tackle complexity in a large single page application.

Installation Guide Of Node.js

1) Install Node.js version 10.x and above. Check the verification via this command:

node -v

2)The node package manager 6.7 or above (NPM) also installed

3)A code editor: Visual Studio Code is highly recommended

4)Vue’s latest version, installed globally on your machine

5)Vue CLI 3.0 installed on your machine. To do this, uninstall the old CLI version first:

npm uninstall -g vue-cli

then install the new one:

npm install -g @vue/cli

  1. Download a Vue Mixins starter project
  2. Unzip the downloaded project
  3. Navigate into the unzipped file and run the command to keep all the dependencies up-to-date:
  4. npm install
In this tutorial, we will understand the Vue.js lifecycle hooks. You will gain a depth understanding of how components create and destroy behind the scene.

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.

This diagram from the official Vue.js documentation captures the Vue.js Instance Lifecycle:

vue

BeforeCreate

The beforeCreate hook runs at the very initialization of your component. data has not been made reactive, and events have not been set up yet:

<script>

export default {

beforeCreate()

{    console.log(‘At this point, events and lifecycle have been initialized.’)  }

}

</script>

You can check out the interface by running your application in the development environment.

npm run serve

Created()

You are able to access reactive data and events that are active with the created hook. Templates and Virtual DOM have not yet been mounted or rendered:

<script>

export default {

name: ‘Test’,

data() {

return {

books: 0

}

},

created() {

alert(‘Created hook has been called’);

console.log(`books is of type ${typeof this.books}`);

}

}

</script>

Understanding Mounting Hooks

Mounting hooks are often the most used hooks. They allow you to access your component immediately before and after the first render. They do not, however, run during server-side rendering.

Use mounting hooks if you need to access or modify the DOM of your component immediately before or after the initial render.

Note: Use created (or created and activated for keep-alive components) for this instead. Especially if you need that data during server-side rendering.

beforeMount

The beforeMount hook runs right before the initial render happens and after the template or render functions have been compiled:

<script>

export default {

beforeMount()

{    console.log(`At this point, vm.$el has not been created yet.`)  }

}

</script>

mounted

In the mounted hook, you will have full access to the reactive component, templates, and rendered DOM (via this.$el).

Use mounted for modifying the DOM—particularly when integrating non-Vue libraries:

<template>

<div ref=”example-element”>Example component.</div>

</template>

<script>

export default {

mounted()

{    console.log(`At this point, vm.$el has been created and el has been replaced.`);    console.log(this.$el.textContent) // Example component.  }

}

</script>

Understanding Updating Hooks

Updating hooks are called whenever a reactive property used by your component changes or something else causes it to re-render. They allow you to hook into the watch-compute-render cycle for your component.

Use updating hooks if you need to know when your component re-renders, perhaps for debugging or profiling.

beforeUpdate

The beforeUpdate hook runs after data changes on your component and the update cycle begins, right before the DOM is patched and re-rendered.

Use beforeUpdate if you need to get the new state of any reactive data on your component before it actually gets rendered:

<template>

<div ref=”example-element”>{

{counter}

}

</div>

</template>

<script>

export default {

data() {

return {      counter: 0    }

},

created() {

setInterval(() => {

this.counter++

},1000)

},

beforeUpdate() {

console.log(`At this point, Virtual DOM has not re-rendered or patched yet.`)

// Logs the counter value every second, before the DOM updates.

console.log(this.counter)  }

}

</script>

updated

This lifecycle hook is called just after a DOM update has occurred, so this means immediately after the beforeUpdate hook is called. DOM related operations can be performed here, although it is not advisable to change state inside this hook as Vue already provides platforms specifically for that.

<template>

<div ref=”example-element”>{

{counter}

}</div>

</template>

<script>

export default {

data() {

return {      counter: 0    }

},

created() {

setInterval(() => {

this.counter++

}, 1000)

},

updated() {

console.log(`At this point, Virtual DOM has re-rendered and patched.`)

// Fired every second, should always be true

console.log(+this.$refs[‘example-element’].textContent === this.counter)  }

}

</script>

Understanding Destruction Hooks

Destruction hooks allow you to perform actions when your component is destroyed, such as cleanup or analytics sending. They fire when your component is being torn down and removed from the DOM.

beforeDestroy

This Vue lifecycle hook is called just before a Vue instance is destroyed, the instance and all the functionalities are still intact and working here. This is the stage where you can do resource management, delete variables and clean up the component.

<script>

export default {

data() {

return {

exampleLeakyProperty: ‘This represents a property that will leak memory if not cleaned up.’    }

},

beforeDestroy() {

console.log(`At this point, watchers, child components, and event listeners have not been teared down yet.`)

// Perform the teardown procedure for exampleLeakyProperty.

// (In this case, effectively nothing)

this.exampleLeakyProperty = null    delete this.exampleLeakyProperty

}

}

</script>

destroyed()

This is the final stage of the Vue lifecycle where all the child Vue instances have been destroyed, things like event listeners and all directives have been unbound at this stage. It gets invoked after running destroy on the object.

<script>

import ExampleAnalyticsService from ‘./example-analytics-service’

export default {

destroyed() {

console.log(`At this point, watchers, child components, and event listeners have been torn down.`)

console.log(this)    ExampleAnalyticsService.informService(‘Component destroyed.’)  }

}

</script>

Conclusion

In this article, you were introduced to different lifecycle hooks available in the Vue.js Instance Lifecycle. You explored the different use cases for creation hooks, mounting hooks, updating hooks, and destruction hooks.

Check out –Â