created() and mounted()in Vue.js

The steps in Vue lifecycle are beforCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed. If the Vue instance is created created () hook allows you to add code to be run. Let’s look at the differences. Reactive data can be accessed when the processing of the options is finished and you can also change them if you want. You cannot do any DOM manipulations because DOM has not been mounted at this stage. created is called earlier in order to trigger actions like data fetching from API backend. Created will not wait for all of the async operations to complete before moving on to the next stage when making API call.

An example for created:

<script>

export default {

  data() {

    return {

      property: 'Blank'

    }

  },

 

  computed: {

    propertyComputed() {

      console.log('I change when this.property changes.')

      return this.property

    }

  },

 

  created() {

    this.property = 'Example property update.'

    console.log('propertyComputed will update, as this.property is now reactive.')

  }

}

</script>

Mounted is the most-often used hook in the lifecycle. mounted() is called after DOM has been mounted so you can access  the reactive component, templates, and DOM elements and manipulate them. In Server Side Rendering created()is used over mounted() because mounted() is not present in it.

An example for mounted hook:

<template>

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

</template>

 

<script>

export default {

  mounted() {

    console.log(this.$el.textContent) // I'm text inside the component.

  }

}

</script>