Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 978
Mukund Kumar Avatar asked Nov 08 '17 16:11

Mukund Kumar


People also ask

What is navigation Guard Vue?

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.

What is router view in Vue?

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.

How do I find out my current route Vue?

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 .


Video Answer


1 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, 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.

like image 64
thanksd Avatar answered Nov 14 '22 08:11

thanksd