Global route guard settings

The global pre-guard can perform some operations before routing jumps, such as verifying whether the user is logged in. The hook function of the global front guard is named beforeEach.

In Vue Router, a global pre-guard can be implemented by adding a beforeEach guard when the router is instantiated. Here is an example:

import Vue from 'vue'  
import Router from 'vue-router'  
  
Vue.use(Router)  
  
const router = new Router({  
  routes: [  
    // ...  
  ]  
})  
  
router.beforeEach((to, from, next) => {  
  // 在这里进行全局前置守卫的操作,如验证用户是否已登录  
  // to是即将要进入的目标路由对象  
  // from是当前导航正要离开的路由  
  // next是一个函数,一定要调用该方法来 resolve 这个钩子  
  if (to.path === '/login') {  
    // 如果目标路径是登录页面,则不进行任何操作  
    next()  
  }else if (getStorage()) {
    // 验证是否有token
    next()
    } else {  
    // 如果目标路径不是登录页面,则需要进行登录验证操作  
    // ...  
    next()  
  }  
})  
  
export default router

        In this example, the hook function of the global front guard is beforeEach, which receives three parameters: to, from, and next. If the target path is a login page, call the next() method directly for routing jump; if the target path is not a login page, you need to perform login verification and other operations, and finally call the next() method for routing jump.

Guess you like

Origin blog.csdn.net/m0_64186396/article/details/131859392