What is navigation guard

1. Official definition

The provided navigational guard is mainly used to guard navigation by jumping or canceling. There are several opportunities for embedding route navigation: global, single route proprietary, or component level.

2. Own understanding

Navigation ward is in the process of routing jump some hooks, more straightforward routing is the process of a big jump, after this big before the process is divided into jump, and so on small process, has a function in each process, this function allows you to operate the timing of some of the other things, such as the jump before login authentication and so on, this is the navigation.

Second, use the navigation guard

1. Installation package

NPM import NPM install vue-router --save CNPM import CNPM install vue-router --save If Taobao image is not installed, install NPM install -g CNPM first --registry=https://registry.npm.taobao.orgCopy the code

2. Global guard

A hook function that operates directly on a routing instance. This hook function is triggered by all routing configuration components. The hook functions are executed in order beforeEach, beforeResolve (2.5+), and afterEach

BeforeEach:

This hook is triggered before a route jump. The parameters include to,from, and next (the parameters will be described separately). This hook is mainly used for login authentication.

BeforeResolve (+ 2.5)

BeforeEach this hook is similar to beforeEach. It is triggered before a route. BeforeEach is different from beforeEach.

The difference is that the parse guard is called before the navigation is confirmed and after all the intra-component guards and asynchronous routing components have been parsed. That is, after beforeRouteEnter and before afterEach within the component.

AfterEach:

In contrast to beforeEach, it is triggered after the route jump is complete. The parameters include to,from without next (parameters described separately). It occurs after beforeEach and beforeResolve, and before beforeRouteEnter.

Their use is as follows:

Route. beforeEach((to, from, next) => {// To the path to be accessed // From represents the path to jump from // Next is a function, // next() next('/login')Copy the code

Small cases:

For example, our background management system basically needs to be logged in before operation, so whether to log in or not should be determined before route jump. If not, it is forced to jump to the login page. The code is as follows: Router module

import Vue from "vue"; import VueRouter from "vue-router"; import Login from ".. /components/Login"; import Home from ".. /components/Home"; import Welcome from ".. /components/Welcome"; import User from ".. /components/User/User"; Vue.use(VueRouter); const router = new VueRouter({ routes: [ { path: "/", redirect: "/login" }, { path: "/login", component: Login }, { path: "/home", component: Home, redirect: 'welcome', children: [ { path: '/welcome', component: Welcome }, { path: '/users', component: User }, ] } ] }); Router. beforeEach((to, from, next) => {if (to.path === '/login') return next(); / / access token const tokenStr = window. The sessionStorage. The getItem (' token ') if (! tokenStr) return next('/login') next() }) export default router;Copy the code

3. A single route is used exclusively

Hook is a hook function that can be set in a single route configuration, as in the example below, where a component like Foo has such a hook function. Currently he has only one hook function beforeEnter.

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

BeforeEnter is exactly the same as beforeEach, if both are set it is executed immediately after beforeEach, with the parameters to, from, and next

A small case

Authentication is required only when a route is entered. Use the route meta information to add meta to the route configuration

const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, children: [ { path: 'bar', component: Bar, // a meta field meta: { requiresAuth: true } } ] } ] }) router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { // this route requires auth, check if logged in // if not, redirect to login page. if (! auth.loggedIn()) { next({ path: '/login', query: { redirect: To.fullpath}})} else {next()}} else {next() // Make sure to call next()}})Copy the code

4. Component level

Is a hook function that executes within a component. It is similar to a lifecycle within a component, and is equivalent to a lifecycle hook function that is added to a component configured with routing. In order of execution, the hook functions include beforeRouteEnter, beforeRouteUpdate (2.2+), and beforeRouteLeave.

<template> ... </template> export default{ data(){ //... }, beforeRouteEnter (to, from, next) {// Call the render component before the corresponding route is confirmed // no! Can!!!! }, 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, the component instance will be reused as // renders the same foo component when jumping between /foo/1 and /foo/2. And the hook will be called in that case. // This'}, beforeRouteLeave (to, from, next) {// This'}} <style>... </style>Copy the code

beforeRouteEnter:

Called before route entry. Parameters include to, from, and next. 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. That is, it fires before the beforeCreate life cycle. In this hook function, you can access the component instance by passing a callback to Next. When the navigation is confirmed, execute the callback and take the component instance as an argument to the callback method. You can request the server to retrieve the data from the guard. When it is successfully retrieved and routed, call next and assign values to the component instance via the VM in the callback. To ensure full access to component instances).

BeforeRouteEnter (to, from, next) {this === undefined next(vm => {// use 'VM' to access component instance})}Copy the code

BeforeRouteUpdate (2.2 + v):

Called when the current route changes and the component is being reused, the instance can be accessed through this. Parameters include to, from, and next. Some students may ask, what is a route change or what is a component being reused?

For a path /foo/:id with dynamic parameters, the component instance is reused when it jumps between /foo/1 and /foo/2, and the guard is called when the current route query changes

beforeRouteLeave

Called when navigating away from the corresponding route of the component and accessing the component instance this with parameters including to, from, and next.

Third, summary

Global routing hook:

BeforeEach (to,from, next), beforeResolve(to,from, next), afterEach(to,from);

Exclusive routing hook:

BeforeEnter (to, from, next);

Component routing hooks:

BeforeRouteEnter (to,from, next), beforeRouteUpdate(to,from, next), beforeRouteLeave(to,from, next)

Navigation guard callback parameter

To: indicates the destination route object.

From: the route object to leave.

Next: It is the most important parameter. It is like the string of Buddha beads, connecting them one by one. The following points should be kept in mind:

1. Whenever a hook with a next parameter is involved, next() must be called to proceed to the next hook, otherwise the route will stop.

2. Call next(false) to interrupt 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. (Mainly used to deal with failure of login authentication)

Next (‘/’) or next({path: ‘/’}): jump to a different address. This means that the current navigation is interrupted and a new navigation is performed. Passable parameters are the same as the router.push option.

BeforeRouteEnter next((VM)=>{}) receives a callback argument that is the instance vm of the current component. This callback is called after Mounted, that is, the last hook to execute all navigationguard and lifecycle functions.

5. Next (error): (v2.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 ().

When clicking Switch Route:

beforeRouterLeave–>beforeEach–>beforeEnter–>beforeRouteEnter–>beforeResolve–>afterEach–>beforeCreate–>created–>b EforeMount –> Mounted –>beforeRouteEnter next callback

When routing is updated:

BeforeRouteUpdate Official document