Reputation: 3062
I use VueJS's mounted
hook in my "container" components to fetch data that builds the view. When that container is destroyed, I use the beforeDestroy
and destroyed
life cycle hooks to "clean up" the component.
These three hooks are not called when the route has changed to the same route, but with different parameters. The suggested way to handle this is by listening for $route
changes in watch
like so:
watch: {
'$route' (to, from) {
this.id = to.params.id
this.getPageData()
}
}
However, instead of copying the logic from mounted
, beforeDestroy
, and destroyed
, I was hoping to do something like this:
watch: {
'$route' (to, from) {
// Manually run lifecycle clean-up hooks
this.beforeDestroy()
this.destroyed()
// Update Id, and run mounted
this.id = to.params.id
this.mounted()
}
}
Unfortunately, it looks like the hooks are not exposed on $vm
. Is there a way to accomplish this that I am not aware of? Am I missing something obvious? Or is there a better / preferred approach?
Upvotes: 1
Views: 2741
Reputation: 15696
You could extract your code inside each lifecycle hook into a component method, and then call that method in both places. Here is an example:
mounted: function() {
this.__mounted();
},
methods: {
__mounted() {
//mounted code here
}
},
watch: {
'$route' (to, from) {
this.__mounted();
}
}
Upvotes: 4