Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the created and mounted events in Vue.js

People also ask

What is created () in Vue?

created() and mounted()in Vue.js 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.

What is mounted () in VUE JS?

May 11, 2020. The mounted() hook is the most commonly used lifecycle hook in Vue. Vue calls the mounted() hook when your component is added to the DOM. It is most often used to send an HTTP request to fetch data that the component will then render.

What are custom events in Vue?

Vue takes an approach similar to the HTML DOM events. An element will "emit" an event and the data from that event. This is a robust way to handle custom events because we know that a child component has inputs (props) and outputs (custom events).

What are the lifecycle methods of Vuejs?

Each Vue component instance goes through a series of initialization steps when it's created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes.


created() : since the processing of the options is finished you have access to reactive data properties and change them if you want. At this stage DOM has not been mounted or added yet. So you cannot do any DOM manipulation here

mounted(): called after the DOM has been mounted or rendered. Here you have access to the DOM elements and DOM manipulation can be performed for example get the innerHTML:

console.log(element.innerHTML)

So your questions:

  1. Is there any case where created would be used over mounted?

Created is generally used for fetching data from backend API and setting it to data properties. But in SSR mounted() hook is not present you need to perform tasks like fetching data in created hook only

  1. What can I use the created event for, in real-life (real-code) situation?

For fetching any initial required data to be rendered(like JSON) from external API and assigning it to any reactive data properties

data:{
    myJson : null,
    errors: null
},
created(){
    //pseudo code
    database.get().then((res) => {
        this.myJson = res.data;
    }).catch((err) => {
        this.errors = err;
    });
}