This is the 10th day of my participation in the August Text Challenge.More challenges in August

One, global guard

1. Global front-guard: router. BeforeEach

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) = > {
  // ...
})
Copy the code

Each guard method takes three arguments:

  1. To: Route: indicates the destination Route to be entered
  2. From: Route: indicates the Route that the current navigation is about to leave
  3. next: FunctionBe sure to call this methodresolveThis hook. Execution effect dependencenextMethod invocation parameters.

Next () : Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.

Next (false) : interrupts current navigation. If the browser URL changes (either manually by the user or by the browser back button), the URL is reset to the address corresponding to the FROM route.

Next (‘/’) or next({path: ‘/’}) : jumps to a different address. The current navigation is interrupted and a new navigation is performed. You can pass any location object to next, and you can set options like replace: True, name: ‘home’, and any options used in router-link’s to prop or router.push.

Next (error) : (2.4.0+) If the argument passed to Next is an error instance, the navigation is terminated and the error is passed to the callback registered with router.onerror ().

/ / sample
router.beforeEach((to, from, next) = > {
  if(to.name ! = ='Login' && !isAuthenticated) next({ name: 'Login' })
  else next()
})
Copy the code

Router. BeforeResolve

In 2.5.0+ you can register a global guard with router.beforeResolve. This is similar to router.beforeeach, except that the parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components are parsed.

3. Global post-hook router.aftereach

The global post-hook, unlike the front-guard, does not accept the next function or change the navigation itself:

router.afterEach((to, from) = > {
  // ...
})
Copy the code

Route exclusive guard

Define beforeEnter guard directly on route configuration:

const router = new VueRouter({
  routes: [{path: '/foo'.component: Foo,
      beforeEnter: (to, from, next) = > {
        // ...}}}])Copy the code

The guard inside the component

Define the following route navigators directly within the routing component:

  • beforeRouteEnter
  • beforeRouteUpdate(new) 2.2
  • beforeRouteLeave
const Foo = {
  template: `... `,
  beforeRouteEnter (to, from, next) {
    // called before the corresponding route to render the component is confirmed
    / / no! Can!!!! Get component instance 'this'
    // Because the component instance has not been created before the guard executes
  },
  beforeRouteUpdate (to, from, next) {
    // Called when the current route changes but the component is being reused
    // For example, for a path /foo/:id with dynamic parameters, when jumping between /foo/1 and /foo/2,
    // Since the same Foo component will be rendered, the component instance will be reused. And the hook will be called in that case.
    // Access component instance 'this'
  },
  beforeRouteLeave (to, from, next) {
    // called when navigating away from the component's corresponding route
    // Access component instance 'this'}}Copy the code

The beforeRouteEnter guard cannot access this because the guard is called before navigation confirmation, so the upcoming new component has not yet been created.

However, you can access the component instance by passing a callback to Next. The callback is executed when the navigation is validated, and the component instance is taken as an argument to the callback method.

beforeRouteEnter (to, from, next) {
  next(vm= > {
    // Access component instances through 'VM'})}Copy the code

Note that beforeRouteEnter is the only guard that supports passing a callback to Next. For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing callbacks are not supported because they are not necessary.

beforeRouteUpdate (to, from, next) {
  // just use `this`
  this.name = to.params.name
  next()
}
Copy the code

This exit guard is usually used to prevent the user from leaving suddenly before saving the changes, such as a confirmation exit popup before leaving. This navigation can be cancelled by next(false).

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('Do you really want to leave? you have unsaved changes! ')
  if (answer) {
    next()
  } else {
    next(false)}}Copy the code