Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which lifecycle hook to use for initialization?

Tags:

vue.js

In the example below I use created lifecycle to subscribe to event service. Is it a normal practice? Is there a more appropriate way or lifecycle method to do this kind of stuff?

const ViewComponent = {
  data(){
    return {
      pathname: window.location.pathname
    }
  },
  created(){
    eventService.on('routeResolved', (route) => {
      this.pathname = route.pathname
    })    
  },
  computed: {
    component () {
     return routes[this.pathname]
    }
  },
  render (h) { 
    return h(this.component) 
  }
}
like image 937
manidos Avatar asked Apr 25 '26 10:04

manidos


1 Answers

Which lifecycle method you use for initialization depends entirely on what you need access to. If you need to manipulate the DOM in any way, you cannot do that until the mounted lifecycle event. For setting up an event handler like you are in the question, using the created lifecycle event is perfectly fine.

Mainly for one-time initialization actions, you will choose either created or mounted. If you need something done every time the component receives new properties you might use beforeUpdated or updated.

Take a look at the documentation for a full description.

like image 51
Bert Avatar answered Apr 27 '26 09:04

Bert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!