Debug School

rakesh kumar
rakesh kumar

Posted on

Vue js Life Cycle

Difference Between the Created and Mounted Events
vue-js-lifecycle-hooks
vue-lifecycle-which-happens-before-page-renders
vue-lifecycle-which-happens-before-page-renders
vue-lifecycle-which-happens-before-page-renders
vue-lifecycle-which-happens-before-page-renders
vue-js-lifecycle-hooks
how-to-use-vue-life-cycle-hooks-for-hitting-an-api-in-vue-js-without-clicking-on
vue-lifecycle-which-happens-before-page-renders

video
Life Cycle

QUESTION:
1.explain how activated , deactivated and error captured works
ue-js-lifecycle-hooks
2.How to use VUE-life cycle hooks for hitting an API in vue.js without clicking on any button.
How to use VUE-life cycle hooks for hitting an API in vue.js without clicking on any button?

The Vue instance
The core of Vue.js is its instance. Every Vue application starts by creating one and it is an object that will help you to create your desired behavior.

The Vue instance contains different options[1]: data, props, template, methods, computed, watchers, lifecycles and much more.

As you can imagine the instance is the responsible for different things, for example setting data observation, compiling the template, mounting the instance to the DOM, updating the DOM when data changes and others. I invite you to read the documentation here if you are interested to know more about all these arguments.

The Vue lifecycle hooks
The lifecycle hooks are functions that give you the opportunity to add code at specific stages.

There are 11:

  1. beforeCreate
  2. create
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. activated
  8. deactivated
  9. beforeDestroy
  10. destroyed
  11. errorCaptured

The beforeCreate, created, beforeMount, mounted and errorCaptured hooks will be executed automatically, all the others will be executed when something happens.

We will explore them one by one with examples so you can understand them without any doubts.

beforeCreate:
It is called immediately after the instance has been initialized and before that all the options[1] will be processed.

Called during server-side rendering

created:
It is called right after the instance has been created and after that all the options[1] have been set up.

Called during server-side rendering

beforeMount:
It is called right before the mounting of the DOM begins.

Called on the client-side

mounted:
It is called when the instance has been mounted and the el(the DOM) has been replaced.

Called on the client-side

beforeUpdate:
It is called when some data changes and before the DOM has been re-rendered.

Called on the client-side

updated:
It is called when some data changed and the DOM has been re-rendered.

Called on the client-side

activated:
This hook is used for components (You can read more about it here), it allows you to know when a component inside the tag is toggled ON.

Called on the client-side

deactivated:
This hook is used also for components, it allows you to know when a component inside the tag is toggled OFF.

Called on the client-side

beforeDestroy:
It is called right before the Vue instance is destroyed. At this stage the instance is still fully functional.

Called on the client-side

destroyed:
It is called after the Vue instance has been destroyed, this doesn’t mean that it will remove all the code from the DOM but that it will remove all the Java Script logic and the instance will not exist anymore.

Called on the client-side

errorCaptured:
This hook confused me in the beginning, also because the docs only says this:

Called when an error from any descendent component is captured. The hook receives three arguments: the error, the component instance that triggered the error, and a string containing information on where the error was captured. The hook can return false to stop the error from propagating further.

Based on my research, it is called by a “parent” component to handle an error from a “child” component. It is not accessible from the main instance but only from a component with children.

What-are-lifecycle-hooks-in-vue-js

What-are-lifecycle-hooks-in-vue-js
Lifecycle hooks are pre-defined methods that get executed in a certain order, starting from the initialization of the Vue instance to its destruction.

Below is a diagram that indicates the Vue JS lifecycle hooks sequence.

Image description
Image description
Image description

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

beforeCreate
beforeCreate is the first lifecycle hook that gets called in Vue JS. beforeCreate is called right after a new Vue instance is initialized. Here, the computed properties, watchers, events, data properties, etc., are not set up.

<script>
  export default {
    beforeCreate() {
      console.log('beforeCreate hook called');
    }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

created
created is the next lifecycle hook that gets called after the beforeCreate hook. Here, the computed properties, watchers, events, data properties, etc., are also activated.

<script>
  export default {
    data() {
      return {
        msg: "Hello World",
      }
    }
    created() {
      console.log('created hook called', this.msg);
    }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

We will be able to access the data properties that were not accessible in the previous hook.

beforeMount
beforeMount is the next lifecycle hook that gets called after the created hook and right before the Vue instance is mounted on the DOM. The template and the styles are all compiled here, but the DOM cannot be manipulated yet.

<script>
  export default {
    beforeMount() {
      console.log('beforeMount hook called');
    }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

mounted
mounted is the next lifecycle hook that gets called after the beforeMount hook and right after the Vue instance has been mounted. The app component or any other component becomes functional and is ready to use.

<script>
  export default {
    mounted() {
      alert('mounted has been called'); 
     }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

beforeUpdate
beforeUpdate is the next lifecycle hook called after the mounted hook. beforeUpdate is called any time a change is made to the data that requires the DOM to be updated.

<template>
  <p> 
    {{ msg }}
  </p>
</template>

<script>
   export default {
     data() {
       return {
         msg: "Hello World",
       }
     },
     beforeUpdate(){
       console.log('beforeUpdate hook called');
     },
     mounted(){
       this.$data.hello= 'This is Shubham Kshatriya!';
     }
   }
</script>
Enter fullscreen mode Exit fullscreen mode

updated
updated is the next lifecycle hook. updated is called after the beforeUpdate hook and just after a DOM update has occurred.

<template>
  <p> 
    {{ msg }}
  </p>
</template>

<script>
   export default {
     data() {
       return {
         msg: "Hello World",
       }
     },
     beforeUpdate(){
       console.log('beforeUpdate hook called');
     },
     updated(){
       console.log('updated hook called');
     },
     mounted(){
       this.$data.hello= 'This is Shubham Kshatriya!';
     }
   }
</script>
Enter fullscreen mode Exit fullscreen mode

beforeDestroy
The beforeDestroy hook is called just before a Vue instance is destroyed. The instance and all the methods are still functional. We can do resource management here.

<script>
   export default {
     data() {
       return {
         msg: "Hello World!",
       }
     },
     beforeDestroy() {
       console.log('beforeDestroy hook called');
       this.msg = null
       delete this.msg;
     }
  }
</script>
Enter fullscreen mode Exit fullscreen mode

destroyed
destroyed is the last stage lifecycle hook, where the entire Vue instance gets destroyed. Event listeners, mixins, and all directives get unbounded here.

<script>
   export default {
     destroyed() {
       this.$destroy() 
       console.log('destroyed hook called')
     }
   }
</script>
Enter fullscreen mode Exit fullscreen mode

ANOTHER EXAMPLE

understanding-vuejs-lifecycle

Understanding Vuejs Lifecycle hooks

A component in Vuejs has a lifecycle which is being managed by Vue itself when it creates the component, mounts the component to the DOM, updates the component and destroy the components. In order words, Each component has what is known as lifecycle events — its birth, life events like changes and death. We can tap into key moments in that lifecycle by implementing one or more lifecycle hooks that gets called by Vue itself thereby giving us the opportunity to add our own code at specific stages of a component lifetime.

Vue has eight lifecycle hooks, and the key to remembering them is to know that four of them are event that get triggered indicating that the actual event will happen. They start with “before” prior to the actual hooks and are fired before the actual hooks.

Lets see these hooks in action.

beforeCreate — This is the first hook that gets called after the Vue instance has been initialized. At this stage, data observation (reactivity), events, computed properties and watchers are yet to be set up. Therefore , we cannot interact with any parts of the component.

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },
  beforeCreate() {
    console.log('I am the first hook to get called!');
    console.log(`You can see that my data property is ${typeof this.counter}`); // undefined
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

*Created *— This hook is called after the instance is created. At this stage, the instance has finished processing, data observation (reactivity), computed properties, methods, watchers and event callbacks have been set up. You can’t interact with the DOM at this stage because your component has not been mounted. The $el property is not also available yet.

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },
  created() {
    console.log('I am the created hook.');
    console.log(`You can now see that my data property is ${typeof this.counter}`);
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

beforeMount — At this stage, the template is compiled, either from the template or render options, or from the outerHTML of the element that Vue was initialized to. The template isn’t rendered yet and the $el method doesn’t exist either. Please note that this hook is not called during sever-side rendering.

<script>
export default {
  beforeMount() {
    console.log(`I am ready to be rendered.!`)
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

*Mounted *— Called after the instance has been mounted, where el property is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called. The component becomes fully functional after the mounted hook is called and we can fully interact with it.

One thing to take note of is that the mounted hook doesn’t guarantee that the element has been added to DOM. To execute a code that is DOM dependent at this stage, put the code inside a callback method to the Vue.nextTick() function (Vue.nextTick() defers its callback to be executed after the next DOM update cycle). See the example below:

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

<script>
export default {
  mounted() {
    // Element might not have been added to the DOM yet
    this.$nextTick(() => {
        // Element has been definitely added to the DOM
       console.log(this.$el.textContent); // I'm text inside the component.
    }
  }
}
</script>

Enter fullscreen mode Exit fullscreen mode

*beforeUpdate *— It is called anytime changes are made to our data and the DOM needs to be updated, right before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to manually remove an added event listeners. This hook is not called during server-side rendering, because only the initial render is performed at server-side.

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },

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

  created() {
    setInterval(() => {
      this.counter++
    }, 1000)
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Updated — hook is fired after a change has been made. The component’s DOM would 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.

Note that updated does not guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use vm.$nextTick inside of updated:

<template>
  <p ref="dom-element">{{counter}}</p>
</template>
<script>
export default {
  data() {
    return {
      counter: 0
    }
  },

  updated() {
    // Fired every second, should always be true
    console.log(+this.$refs['dom-element'].textContent === this.counter)
  },

  created() {
    setInterval(() => {
      this.counter++
    }, 1000)
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

beforeDestroy — Called right before a Vue instance is destroyed. At this stage the instance is still fully functional. You can perform necessary cleanups here. Please note that this hook is not called during sever-side rendering.

<script>
export default {
  data() {
    return {
      counter: 0
    }
  },

  beforeDestroy() {
    // Clean up the counter.
    // (In this case, effectively nothing)
    this.counter = null
    delete this.counter
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

Destroyed — Called 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. Please note that this hook is not called during sever-side rendering.

<script>
import DestroyerNotifierService from './notifier'

export default {
  destroyed() {
    console.log(this) // There's practically nothing here!
    DestroyerNotifierService.informThem('Component destroyed')
  }
}
</script>
Enter fullscreen mode Exit fullscreen mode

All lifecycle hooks automatically have their this context bound to the component instance, so that you can access data, computed properties, and methods. This means you should not use an arrow function to define a lifecycle method (e.g. created: () => this.fetchTodos()). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.fetchTodos will be undefined.

ANOTHER EXAMPLE

understanding-vuejs-lifecycle

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)