Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use created() method in vue?

I have learned life cycle hooks of Vue.js but didn't find any practical scenario where created() function is used ?

I know that created() function can access reactive data and events but cannot access DOM element. But actually I don't know how to use it. Please someone help me providing practical scenario where Created() function is used . Thanks in advance.

like image 489
Diwas Poudel Avatar asked Oct 15 '18 07:10

Diwas Poudel


2 Answers

A lot of people use the Global Event Bus pattern in Vue:

https://alligator.io/vuejs/global-event-bus/

An example of that page which sets up an event listener has this example:

EventBus.$on('i-got-clicked', clickCount => {
  console.log(`Oh, that's nice. It's gotten ${clickCount} clicks! :)`)
});

This is an event you could set up before the DOM template has finished rendering for this particular component. If you would wait on the DOM template to finish here you might miss a click. You simply want to do this as soon as possible.

Just like when your component fires an AJAX request, you don't necessarily always have to wait for the DOM to have finished rendering your component. A lot of times you can fire the request straight away. So why wouldn't you want to shave off some time and fire the AJAX request straight away?

Anything that is in your mounted hook and does not need the DOM, can be moved into a created hook so it will be executed sooner in your Vue lifecycle.

like image 188
Stephan-v Avatar answered Oct 04 '22 15:10

Stephan-v


Have a look at this page on the vue site

According to the diagram:

the created method will be called before component template is made. so you can not access template but you can change values that should be used in the template. for example you can convert json props to object or change component static data and ... The only difference 'created' with 'mounted' is that you can perform performance before the template is made

but remember do not change reactive data in created method. because every time that those data changes created method will not be called again. also you do not have access to this.$el in created method

Now, which one you use or which one you need depends on yourself

like image 23
Zoha Avatar answered Oct 04 '22 14:10

Zoha