Vuejs: Event on route change
Setup a watcher on the $route
in your component like this:
watch:{ $route (to, from){ this.show = false; }}
This observes for route changes and when changed ,sets show
to false
If you are using v2.2.0 then there is one more option available to detect changes in $routes.
To react to params changes in the same component, you can watch the $route object:
const User = { template: '...', watch: { '$route' (to, from) { // react to route changes... } }}
Or, use the beforeRouteUpdate guard introduced in 2.2:
const User = { template: '...', beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() }}
Reference: https://router.vuejs.org/en/essentials/dynamic-matching.html
Just in case anyone is looking for how to do it in Typescript, here is the solution:
@Watch('$route', { immediate: true, deep: true })onUrlChange(newVal: Route) { // Some action}
And yes as mentioned by @Coops below, please do not forget to include :
import { Watch } from 'vue-property-decorator';
Edit:Alcalyn made a very good point of using Route type instead of using any:
import { Watch } from 'vue-property-decorator'; import { Route } from 'vue-router';