Sobes.tech
Junior

What is the difference between the created and mounted hooks in Vue.js?

sobes.tech AI

Answer from AI

created is called after the Vue instance is created but before it is mounted to the DOM. Data is reactive, methods and computed properties are available. Suitable for initializing data, performing AJAX requests.

mounted is called after the Vue instance is mounted to the DOM. $el is available, representing the root DOM element. Suitable for working with the DOM, integrating third-party libraries that require the presence of a DOM element.

Hook Call Time $el Available Suitable for
created After instance creation, before mounting No Data initialization, AJAX
mounted After mounting to the DOM Yes Working with DOM, library integration
// Example of using created
created() {
  // Fetch data from API before mounting
  this.fetchData();
},

// Example of using mounted
mounted() {
  // Initialize a library that works with the DOM
  new Chart(this.$refs.myChartCanvas, ...);
}