Difference between beforeRouteUpdate and watching '$route' - Vue.js?

Viewed 20642

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?

2 Answers

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 same UserDetails 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 to this 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.

Related