SoFunction
Updated on 2025-04-05

Vue routing guard, example of restricting front-end page access permissions

Today I will write you an article about vue checking the login status. If it is illegal login, it will jump to the login page.

First, you need to write a route guard. Its principle is that the specific writing method is triggered every time the route changes:

((to, from, next) => {
  next()
})

The beforeEach function has three parameters:

to: The route object to be entered

from: The route that the current navigation is about to leave

next, perform a hook in the pipeline. If the execution is completed, the navigation status is confirmed; otherwise it is false, and the navigation is terminated.

Use Cases

Restrict login function, specific implementation idea: each jump route is to determine the local ('token') status

First find the router/as follows

import Vue from 'vue'
import Router from 'vue-router'
(Router)
 
const router = new Router({
 routes: [{
   path: '/',
   name: 'HelloWorld',
   component: HelloWorld
  },
  {
   path: '/login',
   name: 'login',
   component: login
  }
 ]
})
//The following is the key((to, from, next) => {
 let token = ('token') 
 if ( == '/login') {
  next()
 } else {
  if (token == '' || token == null) {
   next('/login');
  } else {
   next()
  }
 }
 
})
 
export default router;

explain:Written as above, use const router to accept the new Router object, and finally export is exposed

Departing every route jump

let token = ('token') Get local tokens if not, jump to the login page. Very simple logic

The above example of vue routing guard restricting front-end page access is all the content I share with you. I hope you can give you a reference and I hope you can support me more.