Learn the routing guard in vue in 5 minutes

Learn the routing guard in vue in 5 minutes

In the project development, every time the route is switched or the page is refreshed, it is necessary to judge whether the user has logged in. The front-end can judge, and the back-end judges too. Our front-end should also judge.

Vue-router provides navigation hooks: the global front navigation hook beforeEach and the global rear navigation hook afterEach, they will be triggered before and after the route is about to change. So judging whether the user is logged in needs to be judged in the beforeEach navigation hook.

The navigation hook has 3 parameters:
1. to: the target route object that is about to enter;
2. from: the route object that the current navigation is about to leave;
3. next: the next hook function (afterEach) can be entered after calling this method .
  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 the wrong route

beforeEach:
Route configuration file:

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import HomePage from '@/pages/home.vue'
Vue.use(Router)
const router=new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
     {
      path: '/home',
      name: 'home',
      component: HomePage
    },
     {
        path:'*',
        redirect:'/home'
     }
  ],
})
  router.beforeEach((to,from,next)=>{
    console.log(to);
    console.log(from);
    next();
  })
 export default router;

The print result is as follows:

Insert picture description here
the code to achieve user authentication:

router.beforeEach((to, from, next) => {
    //我在这里模仿了一个获取用户信息的方法
  let isLogin = window.sessionStorage.getItem('userInfo');
    if (isLogin) {
        //如果用户信息存在则往下执行。
        next()
    } else {
        //如果用户token不存在则跳转到login页面
        if (to.path === '/login') {
            next()
        } else {
            next('/login')
        }
    }
})

afterEach: The

difference from beforeEach is that afterEach does not receive the third parameter next function, nor does it change the navigation itself. Generally, beforeEach is used the most, afterEach is used less.

router.afterEach((to,from)=>{ //这里不接收next
    console.log(to);
    console.log(from);
})

It's the end! Look at others

Canvas Line Animation
CSS Rotating Rubik's Cube
JS Mini Keyboard
CSS Realistic Elephant

Guess you like

Origin blog.csdn.net/weixin_45820444/article/details/108525860