As we know, to react to params changes in the same component we use beforeRouteUpdate
hook or watching $route
.
watching $route:
const User = {
template: '...',
watch: {
'$route' (to, from) {
// react to route changes...
}
}
}
beforeRouteUpdate Method:
const User = {
template: '...',
beforeRouteUpdate (to, from, next) {
// react to route changes...
next()
}
}
What is the difference between these two? if both are same then why vue router introduced beforeRouteUpdate
?
Watch a free video lesson on Vue School. As the name suggests, the navigation guards provided by Vue router are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.
The RouterView or router-view component is used to display the current route the user is at. Source: vue-router.d.ts /** * Component to display the current route the user is at.
In Vue 2, we have to use the route instance to get the name. To get the name of the current route we have to use this. $route.name .
From the documentation on beforeRouteUpdate
:
called when the route that renders this component has changed, but this component is reused in the new route. For example, for a route with dynamic params
/foo/:id
, when we navigate between/foo/1
and/foo/2
, the sameFoo
component instance will be reused, and this hook will be called when that happens.
The documentation is admittedly unclear that the hook gets called before the value of the $route
object actually changes. That's the difference between this navigation hook and setting a watcher on $route
, which will get called after the value of $route
has changed.
Using the beforeRouteUpdate
navigation guard, you can determine whether or not you want to prevent the route from changing (by not calling next()
) or go to a different route entirely (by passing a different route value like next('/foo')
, next({ name: 'foo' })
, etc.).
Here's an example fiddle that shows when these functions get called.
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