George X
George X

Reputation: 47

What is the difference between the beforeMount and the created lifecycle hook in vuejs

I am still unclear on where I should use the beforeMount and where the created lifecycle hook. It seems to me that in both, the reactive data has been loaded and it is before the DOM has been mounted.

Upvotes: 2

Views: 9656

Answers (2)

Michal Levý
Michal Levý

Reputation: 37903

In most cases it doesn't matter whether you use beforeMount or created but there are some where it matters:

Accessing original DOM element your root Vue component is mounting on

  • can be useful for integration with any server-side rendered framework (php, rails etc.)
  • explanation and example - When to use the lifecycle method beforeMount in vue.js?
  • in created hook this.$el is undefined, in beforeMount it's the original unmodified element, in mounted it's root element created by your component/template

Server-side rendering (Nuxt, Vuepress etc.)

  • docs
  • beforeCreate and created are only hooks called on the server
  • that means you should not use any code which needs window, document or any browser API in created as those will not be present on the server
  • on the other hand code placed in the beforeMount (or mounted) is executed only on the client (browser)

Upvotes: 4

ma_jafari
ma_jafari

Reputation: 1059

The beforeMount hook runs right before the initial render happens and after the template or render functions have been compiled(when vm.$el has not been created yet).

created is the step after initialization of your component(where you are able to access reactive data and events that are active with the created hook. Templates and Virtual DOM have not yet been mounted or rendered)

Upvotes: 2

Related Questions