Vue routing to implement login interception

Vue routing to implement login interception

1. Overview

In project development, every time a route is switched or a page is refreshed, it is necessary to determine whether the user is logged in. The front end can make this judgment, and the back end will also make this judgment. It is best for our front end to also make this judgment.

vue-router provides navigation hooks: global pre-navigation hook beforeEach and global post-navigation hook afterEach, which will be triggered before and after the route is about to change. Therefore, it is necessary to determine whether the user is logged in in the beforeEach navigation hook.

The navigation hook has 3 parameters:

1. to: the target routing object to be entered;

2. from: the route object that the current navigation is about to leave;

3. next: Only after calling this method can you enter the next hook function (afterEach).

next()//Go directly to the route pointed to by to
next(false) //Interrupt the current route
next('route') // Jump to the specified route
next('error') //jump to error route

2. Routing Navigation Guard to Implement Login Interception

Here we use a blank vue project to demonstrate, there are mainly two pages, namely the home page and login.

When visiting the homepage, you must log in, otherwise you will be redirected to the login page.

Create a blank vue project and create Login.vue in src\components

<template>
 <div>This is the login page</div>
</template>

<script>
 export default {
  name: "Login"
 }
</script>

<style scoped>

</style>

Modify src\router\index.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/components/Login'


Vue.use(Router)

const router = new Router({
 mode: 'history', // remove the # in the url
 routes: [
 {
  path: '/login',
  name: 'login',
  meta: {
  title: 'Login',
  requiresAuth: false, // false means no login is required},
  component: Login
 },
 {
  path: '/',
  name: 'HelloWorld',
  meta: {
  title: 'Homepage',
  requiresAuth: true, // true means login is required},
  component: HelloWorld
 },

 ]
})

// Routing interception, determine whether login is required router.beforeEach((to, from, next) => {
 if (to.meta.title) {
 //Determine whether there is a title document.title = to.meta.title;
 }
 // console.log("title",document.title)
 // Use requiresAuth to determine whether the current route navigation requires login if (to.matched.some(record => record.meta.requiresAuth)) {
 let token = localStorage.getItem('token')
 // console.log("token",token)
 // If login access is required, check whether the user is logged in if (!token) {
  next({
  path: '/login',
  query: { redirect: to.fullPath }
  })
 } else {
  next()
 }
 } else {
 next() // Make sure to call next()
 }
})

export default router;

illustrate:

In each route, meta is added. The requiresAuth field is used to indicate whether login is required.

In router.beforeEach, a token check is done. If it is empty, jump to the login page.

Visit Home Page

http://localhost:8080

Will jump to

http://localhost:8080/login?redirect=%2F

The effect is as follows:

Open F12, enter the console, and manually write a token

localStorage.setItem('token', '12345678910')

The effect is as follows:

Visit the homepage again and you can access it normally.

Open Application, delete the value in Local Storage, right click and click Clear

Refresh the page and you will be redirected to the login page.

How about it, isn’t it simple?

The above is the details of how to implement login interception with vue routing. For more information about vue login interception, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Two ways to implement login interception in vue+axios front end (routing interception, http interception)
  • vue-resource request to implement http login interception or routing interception method
  • Vue login intercepts the operation of continuing to jump to the specified page after logging in
  • Vue implements login interception
  • Example code for implementing login interception with vue+axios

<<:  Linux kernel device driver Linux kernel basic notes summary

>>:  Tutorial on how to remotely connect to MySQL database under Linux system

Recommend

Pay attention to the use of HTML tags in web page creation

HTML has attempted to move away from presentation...

Teach you how to implement Vue3 Reactivity

Table of contents Preface start A little thought ...

Vue handwriting loading animation project

When the page is not responding, displaying the l...

Web page HTML ordered list ol and unordered list ul

Lists for organizing data After learning so many ...

Docker-compose tutorial installation and quick start

Table of contents 1. Introduction to Compose 2. C...

MYSQL unlock and lock table introduction

MySQL Lock Overview Compared with other databases...

Detailed explanation of Nginx current limiting configuration

This article uses examples to explain the Nginx c...

js code to realize multi-person chat room

This article example shares the specific code of ...

Detailed explanation of MySQL 8.0 atomic DDL syntax

Table of contents 01 Introduction to Atomic DDL 0...

A record of pitfalls in JS regular matching

I recently discovered a pitfall in regular expres...

How to correctly create MySQL indexes

Indexing is similar to building bibliographic ind...

How to build a K8S cluster and install docker under Hyper-V

If you have installed the Win10 system and want t...