What is a route guard?

Official explanation:

Navigation indicates that the route is changing. True to its name, vue-Router provides navigational guards that are primarily used to guard navigation by jumping or cancelling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level.

To put it simply, a navigational guard is a set of hook functions during a route jump. The route jump is a big process, the big process is divided into before, after and so on small process, in each process has a function, this function allows you to operate on something else, this is the navigation guard. Similar to component lifecycle hook functions

Routing Guard classification

[1] Global guard: refers to a hook function operated directly on a routing instance. It features that all routing configuration components will trigger

  • BeforeEach (to, from, next)
  • BeforeResolve (to, from, next)
  • AfterEach (to, from)

[2] Route guard: a hook function that can also be set during the configuration of a single route

  • BeforeEnter (to, from, next)

[3] Component guard: refers to the hook function executed in the component, which is similar to the life cycle of the component, and is equivalent to the life cycle hook function added for the component configured with routing.

  • BeforeRouteEnter (to, from, next)
  • BeforeRouteUpdate (to, from, next)
  • BeforeRouteLeave (to, from, next)

This section describes the route guard callback parameters

To: indicates the destination route object to be entered.

From: the route object to leave.

Next: The hook function that refers to the next argument must call the next() method to resolve the hook, otherwise the route will break and will not proceed

  • Next () : Goes to the next hook in the pipe. If all hooks are executed, the navigation state is confirmed.
  • Next (false) interrupts the 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({paht: ‘/’}) : jumps to a different address. The current navigation is interrupted and a new navigation is performed. Passable arguments can be the to attribute parameter in the router-link tag or an option in router.push
  • Next (error) : If the argument passed to Next is an instance of error, the navigation is terminated and the error is passed to the callback registered with router.onerror ().

Route guard details

[1] Global resolution guard (beforeEach) : Triggered before route redirects. This hook is mainly used for login authentication, that is, notifying a route before it redirects so that it is too late to notify it again.

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

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

[2] beforeResolve: This hook is similar to beforeEach in that it fires before a route jump, except that it is called before navigation is acknowledged and after guard and asynchronous routing components are resolved within all components, after beforeRouteEnter within each and before afterEach.

[3] afterEach: In contrast to beforeEach, it fires after the jump is complete. It happens after beforeEach and beforeResolve, and before beforeRouteEnter. These hooks do not accept the next function nor change the navigation itself

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

[4] Exclusive guard (beforeEnter) : exactly the same as beforeEach, if both are set, beforeEnter is executed immediately after beforeEach. Define the beforeEnter guard directly on the route configuration

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

[5] Guards in components:

<template>.</template>
<script>
export default{
  data(){
    / /...
  },
  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'}}</script>
<style>.</style>Copy the code

1. BeforeRouteEnter: This hook is called after the global guard beforeEach and exclusive guard beforeEnter, and before global beforeResolve and afterEach. Note that there is no instance of the component in this guard, i.e. this is undefined. Because it fires during the component lifecycle beforeCreate phase, the new component has not yet been created. In this hook function, 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

BeforeRouteUpdate: called when the current route changes and the component is being reused, the instance can be accessed through this.

3. BeforeRouteLeave: called when navigating away from the corresponding route of the component, which can be accessed by component instance this. This departure guard is usually used to prevent the user from leaving suddenly without saving the changes. 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

Complete navigation parsing process

  1. Trigger to enter other routes
  2. Call the component guard beforeRouteLeave to leave the route
  3. Call the global front-guard beforeEach
  4. Call beforeRouteUpdate in the reused component
  5. Call beforeEnter in routing configuration
  6. Parse the asynchronous routing component
  7. Call beforeRouteEnter in the incoming routing component
  8. Call the global parse guard beforeResolve
  9. Navigation confirmed
  10. Call the global afterhook afterEach.
  11. DOM update Mounted is triggered.
  12. Execute the callback passed to Next in the beforeRouteEnter guard.


The article is updated every week. You can search “Front-end highlights” on wechat to read it in the first time, and reply to [Books] to get 200G video materials and 30 PDF books