vue-router hook function implements routing guard

vue-router hook function implements routing guard

Overview

What is Route Guard? The route guard is a bit similar to the ajax request interceptor, which intercepts the request before it is sent and does something before sending the request. The route guard here has a similar meaning. It can be simply understood as stopping you and checking you before you enter the route. Is this a bit like the security guard at the gate of a middle school? Stop you before you enter, and let you in if you have a student ID, but not let you in if you don't have a student ID; of course, the routing guard does more than just stop you before you enter, there are other hook functions to perform other operations;

Vue-router provides us with three types of hook functions to implement routing guards:

1. Global hook function (beforeEach, afterEach)

2. Routing-specific hook function (beforeEnter)

3. Hook functions in components (beforeRouterEnter, beforeRouterUpdate, beforeRouterLeave)

First, let's take a look at the global hook function:

Global hook function

beforeEach:

beforeEach receives three parameters: to, from, and next; to: the route object to be entered; from: the route object to be left; next: the control parameters of the route;

There are four ways to call next:

next(): If everything goes well, call this method to enter the next hook;

next(false): cancel the route navigation. The URL at this time shows the route address that is about to be left.

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

next(error): The route navigation is terminated and the error will be passed to the callback registered by router.onError();

We usually use global hooks to control permissions, such as jumping to the login page when entering a page without logging in, and what level the user needs to reach to access the current page. These are all page permission controls, which can be achieved through the beforeEach hook function:

main.js (global hook functions are usually written in main.js):

// Method hook before entering the route router.beforeEach((to, from, next) => {
  console.log(to, 'prepend the first parameter')
  console.log(from, 'prepend the second parameter')
  console.log(next, 'prepend the third parameter')
  /
    to target route from source route next jump to next route*/
//Here we use local and storange to simulate the verification of 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');
  }
});

AfterEach:

AfterEach, like beforeEach, is a global guard hook and is called in main.js. AfterEach has one less next parameter than beforeEach.

from: the route object that is about to leave;

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

If we have a very long page, and we scroll to a certain position in it, the scroll bar position of the new page will be where the previous page stayed; at this time we can use afterEach to reset it:

//Global route change hook router.afterEach((to, from) => {
  //Restore the scroll bar to the top window.scrollTo(0, 0);
})

Routing-specific hook functions

beforeEneter:

As the name implies, only the specified routes have these hook functions. Usually, we configure these hook functions in the route configuration file. We can only set the hooks before the change, not the hooks after the change.

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 means that the beforeEnter hook will only be triggered when entering /page1. If you enter other pages, it will not be triggered.

Hook function in component

beforeRouteEnter(to,from,next):

Called before the route enters. Because the Vue instance has not been created at this time, beforeEnter is the only hook function that cannot use this;

to: the route object to be entered;

from: the route object that is about to leave;

next: routing control parameters

beforeRouteUpdate(to,from,next):

Called when the route is modified, such as the dynamic route parameter transfer mentioned in our previous article, in this case our beforeRouteUpdate will also be called;

to: the route object to be entered;

from: the route object that is about to leave;

next: routing control parameters;

beforeRouteLeave(to,from,next):

Called when the route leaves the component;

to: the route object to be entered;

from: the route object that is about to leave;

next: routing control parameters

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

When calling a hook function in a component, we usually call it inside the component. For example:

<template>
    <div>
        <h1 id="h1">Home</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 {
    //Call before route enters beforeRouteEnter (to, from, next) {
    window.document.title = "Welcome";
    next();
  },
    //Call beforeRouteUpdate(to,from,next) when the route is modified {

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

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

The above is the details of the vue-router hook function to implement the routing guard. For more information about the vue-router routing guard, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Solve the problem that Vue browser back cannot trigger beforeRouteLeave
  • Detailed explanation of the use of vue router navigation guard (router.beforeEach())
  • vue-router's beforeRouteUpdate does not trigger the problem

<<:  Complete steps to build a squid proxy server in linux

>>:  Detailed explanation of how to use the mysql backup script mysqldump

Recommend

Disable IE Image Toolbar

I just tried it on IE6, and it does show the toolb...

How to track users with JS

Table of contents 1. Synchronous AJAX 2. Asynchro...

Detailed explanation of JavaScript to monitor route changes

Table of contents history pushState() Method push...

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which mea...

Vue.js implements simple timer function

This article example shares the specific code of ...

Description of meta viewport attribute in HTML web page

HTML meta viewport attribute description What is ...

js to achieve star flash effects

This article example shares the specific code of ...

Analysis of the difference between absolute path and relative path in HTML

As shown in the figure: There are many files conne...

Implementation steps for docker-compose to deploy etcd cluster

Table of contents Write docker-compose.yml Run do...

Web page CSS priority is explained in detail for you

Before talking about CSS priority, we need to und...

Summary of horizontal scrolling website design

Horizontal scrolling isn’t appropriate in all situ...

Perfect solution for vertical centering of form elements

Copy code The code is as follows: <!DOCTYPE ht...

JavaScript timer to achieve seamless scrolling of pictures

This article shares the specific code of JavaScri...