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)
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With