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

Mukund Kumar picture Mukund Kumar · Nov 8, 2017 · Viewed 13.8k times · Source

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?

Answer

thanksd picture thanksd · Nov 8, 2017

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 same Foo 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.