Programmers are still struggling with the created and mounted hooks in Vue.js and trying to find out what is the difference between these two. Let’s figure out together and see which method is used for real-life situations covered up in this tutorial.
For the created() hook, after the processing of the options is finished, you can already have access to reactive data properties and change if necessary. At this stage of the process, DOM has not been mounted or added yet; thus, you cannot do any manipulation. The created() hook is used for fetching data from backend API and setting it to data properties. But in SSR, the mounted hook isn’t present and requires the performance of tasks like fetching data in created hook only.
The mounted() hook is called after the DOM has been mounted or rendered which enables you to have access to the DOM elements and you can perform DOM manipulation. Mounting hooks are often the most used ones. The best use case for the mounted hook is if you need to access or alter the DOM of your component immediately before or after the initial render.
To fetch any initial required data to be rendered from external API and assigning it to any reactive data properties, you can choose the created hook like this:
data:{
myJson : null,
errors: null
},
created(){
//pseudo code
database.get().then((res) => {
this.myJson = res.data;
}).catch((err) => {
this.errors = err;
});
}