Reputation: 23211
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
?
Upvotes: 28
Views: 26334
Reputation: 55644
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, given a route with params
/users/:id
, when we navigate between/users/1
and/users/2
, the sameUserDetails
component instance will be reused, and this hook will be called when that happens. Because the component is mounted while this happens, the navigation guard has access tothis
component instance.
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.
Upvotes: 21
Reputation: 598
As @thanksd said $route
is like guard. With watching you can't prevent the route from taking action, but with beforeRouteUpdate
you can do it with next
function. for example you can wait untill your data is fetched then proceed to the component.
You can find more information in vue-router documentation Data Fetching.
Upvotes: 2