Vue router routing guard and authentication

First, let's understand the routing guard:

Routing guard is a bit similar to ajax request interception, which is to stop you before sending the request, and then send the request. The reason here is the same; It is simply understood that before you enter the route, first stop you and check you; Of course, routing guards not only stop you before you enter, but also other hook functions for other operations;

Vue Reuter provides three kinds of hook functions to implement routing guard

1. Global hook function (beforEach, afterEach)
2. Route exclusive hook function (beforeEnter)
3. Hook functions in components (beforerouterEnter, beforerouterUpdate, beforerouterLeave)
Let's first look at the global hook function:

Global hook function:

beforEach:
A total of three parameters are accepted: to, from and next; To: the routing object to be entered; From: the routing object that is about to leave; Next: control parameters of the route (next)
next can be called in four ways:

next(): if everything is normal, call this method to enter the next hook;

next(false): cancel route navigation. The url at this time displays the route address that is about to leave;

next('/ login'): the current route is terminated and enters a new route navigation (the route address can be specified freely)

next(error): the route navigation terminates and the error will be passed to the router Onerror() is in the callback registered;

We generally use global hooks to control permissions. For example, if you enter the page without logging in, you jump to login. What level users in Yuyao can access the current page belongs to page permission control, which can be realized through beforeEach hook function:

The global hook function is usually written in main JS

// Method hook before entering the route
router.beforeEach((to, from, next) => {
  console.log(to, 'Preceding first parameter')
  console.log(from, 'Pre second parameter')
  console.log(next, 'Pre third parameter')
  /
    to Target routing
    from Source routing
    next Jump to next route
  */
//For the time being, local and storange are used to simulate and verify permissions
  if (window.localstorange.getItem("token")) {
    // If it exists, jump directly to the corresponding route
     next();
  } else {
    // If it does not exist, jump to the login page
    next('/login');
  }
});
affterEach:
AfterEach, like beforeEach, belongs to the global guard hook, which is in main JS; AfterEach has one less next parameter than beforeEach;

To: the routing object to be entered;

from: the routing object that is about to leave;

afterEach() is generally used to reset the position of the page scroll bar:

If we have a long page and jump after scrolling to a certain position, the scroll bar position of the new page will be at the position where the previous page stays; At this time, we can use afterEach to reset:
//Hook after global route change
router.afterEach((to, from) => {
  //Returns the scroll bar to the top
  window.scrollTo(0, 0);
})

Route exclusive hook function:

beforeEneter:
The settings of these hooks are usually set in the configuration file of the exclusive hook function, which can only be set after changing the name of the exclusive hook
const router=new VueRouter({
    routes
});
const routes=[
    {
        path:'/page1',
        component:page1,
        children: [
            {
                path: "phone",
                component: phone
            },
            {
                path: "computer",
                component: computer
            },
        ],
//Route exclusive hook function
        beforeEnter:(to,from,next)=>{
            console.log(to);
            console.log(from);
            next(false);
        }
    },
    //The above code is understood as that the beforeEnter hook will be triggered only when you enter / page1. If you enter other pages, it will not be triggered;

Hook function in component:

beforeRouteEnter(to,from,next):
Called before routing, because vue is not created at this time, so beforeEnter is the only hook function that can not use this.

To: the routing object to be entered;

from: the routing object that is about to leave;

next: route control parameters

beforeRouteUpdate(to,from,next):

Call when the route is modified, such as the dynamic route parameter transmission mentioned in our last article. In this case, our beforeRouteUpdate will also be called;

To: the routing object to be entered;

from: the routing object that is about to leave;

next: route control parameters;

beforeRouteLeave(to,from,next):

Called when the route leaves the component;

To: the routing object to be entered;

from: the routing object that is about to leave;

next: route control parameters

Note: because the vue instance has not been created when beforeRouteEnter is triggered, this cannot be used in this hook function. Both beforeRouteUpdate and beforeRouteLeave can access the instance, because the instance has been created when these two functions are triggered;

When calling the hook function in the component, we usually call it inside the component, for example:

<template>
    <div>
        <h1 id="h1">homepage</h1>
        <p>
            <router-link to="/page1/phone">mobile phone</router-link>
            <router-link to="/page1/computer">computer</router-link>
        </p>
        <router-view></router-view>
    </div>
</template>
<script>
    export default {
    //Routing before invocation
  beforeRouteEnter (to, from, next) {
    window.document.title  = "welcome";
    next();
  },
    //Called when the route is modified
  beforeRouteUpdate(to,from,next){

  },
   //Called when the route leaves
  beforeRouteLeave(to,from,next){

  },
        data () {
            return {
                msg: "I am page1 assembly"
            }
        },
    }
</script>    

Keywords: Vue

Added by mikes127 on Wed, 02 Feb 2022 12:51:29 +0200