Vue Method Life Cycle

By ukmodak | May 18th 2022 09:26:00 AM | viewed 342 times

There are eight lifecycle methods:

  • 1 Before create - The beforeCreate hook runs at the initialization of your component - data has not been made reactive, and events have not been set up yet. it is used to store default data.
  • 2 Created - The created hook runs before the templates and Virtual DOM have been mounted or rendered - you are able to access reactive data and events that are active. It is used to call server side function or call any function under method
  • 3 beforeMount - The beforeMount hook runs right before the initial render happens and after the template or render functions have been compiled. Here dom element does not prepared
  • 4 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. Here dom element is prepared and can be access by this.$el
  • 5 Before update - 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 gets rendered. When change input field then call it
  • 6 Updated - The updated hook runs after data changes on your component and the DOM re-renders. Use updated if you need to access the DOM after a property change. After change input field then call it
  • 7 Before destroy - beforeDestroy is fired right before teardown. Your component will still be fully present and functional. Use beforeDestroy if you need to clean up events or reactive subscriptions:
  • 8 Destroyed - By the time you reach the destroyed hook, there’s practically nothing left on your component. Everything that was attached to it has been destroyed. Use destroyed if you need to do any last-minute cleanup or inform a remote server that the component was destroyed
  <div ref="example-element">{{ propertyComputed }}</div>
   <h1>{{ subtotal  }} 
   <h1>{{ shipping   }} 
   <span>{{ author.books.length > 0 ? 'Yes' : 'No' }}
   <button @click="show()">Click me</button>
   <h2 id="view"></h2>


import ExampleAnalyticsService from './example-analytics-service'

export default {
  data() {
    return {
      property: 'Example property.',
	  counter: 0,
	  exampleLeakyProperty: 'This represents a property that will leak memory if not cleaned up.',
	  value1: '',
      result: 0,
	  qty: 1,
      price: 5,
      qty2: 1,
      price2: 5,
      showTotal: false,
	  pow: 0,
      n2: 0,
	  books: [
          'Vue 2 - Advanced Guide',
          'Vue 3 - Basic Guide',
          'Vue 4 - The Mystery'
  beforeCreate() {
    /*console.log('At this point, events and lifecycle have been initialized.');*/
	this.$nextTick(function () {
	this.hardData = {
            n: 21,
            mess: 'hard coded data is used'

  created() {
    console.log('At this point, is now reactive and propertyComputed will update.'); = 'Example property updated.';
	 setInterval(() => {
    }, 1000)
  beforeMount() {
    console.log(`At this point, vm.$el has not been created yet.`)
  mounted() {
    console.log(`At this point, vm.$el has been created and el has been replaced.`);
    console.log(this.$el.textContent) // Example component.
	this.$el.querySelector("input").value = "Enter name";
	this.$el.querySelector("span").innerText = ' you clicked the button';
    this.$el.querySelector("span").style.color = 'pink';
	this.$el.querySelector("#bn").style.display = 'none';
	this.$el.querySelector(".image").src = this.$el.querySelector(".urlinput").value;
	this.$el.querySelector("span").style.backgroundColor ="red";
	this.$nextTick(function () {;  // call method function
  beforeUpdate: function () {
        var data = this.$data;
        data.pow = Number(data.pow);
        if (data.pow + '' === 'NaN' || data.pow < 0) {
            data.pow = 0;
        if (data.pow > 1023) {
            data.pow = 1023;
  updated: function () {
  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
  destroyed() {
    console.log(`At this point, watchers, child components, and event listeners have been torn down.`)
    ExampleAnalyticsService.informService('Component destroyed.')
  watch: {
	value1: function (val) {
		this.value1 = val;
		this.result = 2 * val;
	result: function (val) {
		this.result = val;
  computed: {
     propertyComputed() {
    quantity: {
      get() {
        return `${this.qty}`
      set(theQuantity) {
        this.qty = theQuantity
    priceCalc () {
      return this.qty * this.price
    quantity2: {
      get() {
        return `${this.qty2}`
      set(theQuantity) {
        this.qty2 = theQuantity
    priceCalc2 () {
      return this.qty2 * this.price2
    subtotal () {
      return this.priceCalc + this.priceCalc2
    shipping () {
      return (2 * 10)/ this.subtotal || ''
	publishedBooksMessage() {
      return > 0 ? 'Yes' : 'No'
  methods : {
	show: function(){
			// Setting text in element
			  .innerHTML = "Hi, This is Vue"
			// Hiding text after 2 seconds
			setTimeout(() => {
				   .innerHTML = ""
			}, 2000);
		figure: function () {
            this.$data.n2 = Math.pow(2, this.$data.pow);



A Vue application consists of a root Vue instance created with new Vue, optionally organized into a tree of nested, reusable components. Whenever you create a new Vue project, the Vue instance gets activated by default in the main.js file by this code:

new Vue({
 render: h => h(App),

Setup(Composite API used in vue 3) :

Composition API is a set of APIs that allows us to author Vue components using imported functions instead of declaring options. It is an umbrella term that covers the following APIs:

  • Reactivity API, e.g. ref() and reactive(), that allows us to directly create reactive state, computed state, and watchers.
  • Lifecycle Hooks, e.g. onMounted() and onUnmounted(), that allow us to programmatically hook into the component lifecycle.
  • Dependency Injection, i.e. provide() and inject(), that allow us to leverage Vue's dependency injection system while using Reactivity APIs.

Vue 2 use Option API

Updating Vue 2 Code to(->) Vue 3 Lifecycle Hooks

  • beforeCreate -> use setup()
  • created -> use setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

Other Hook

  • method: A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object.Methods are useful when you need to perform some action with v-on directive on an element to handle events
  • computed: computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model
  • watch: A Watcher in Vue. js is a special feature that allows one to watch a component and perform specified actions when the value of the component changes. It is a more generic way to observe and react to data changes in the Vue instance. Watchers are the most useful when used to perform asynchronous operations. Note: Watchers can change only one property at a time. If multiple component values have to be changed, one can use computed properties.

Total : 20358

Today :12

Today Visit Country :

  • United Kingdom
  • United States
  • China
  • Singapore
  • Russia