只要路由变化就会触发beforeEach函数

    next() 一定要调用该方法来resolve这个钩子

    next() //to 没传参数默认是to

    src/main.js

    1. //路由守卫
    2. router.beforeEach( (to,from,next)=>{
    3. console.log(to) //进入的页面(下一个页面)
    4. console.log(from) //离开之前的页面
    5. console.log(next)
    6. next()
    7. })

    image.png

    封装路由守卫
    1.新建,router/premit.js,将main.js挪过来

    1. import router from "@/router/index";
    2. //路由守卫
    3. router.beforeEach((to, from, next) => {
    4. console.log(to) //进入的页面(下一个页面)
    5. console.log(from) //离开之前的页面
    6. console.log(next)
    7. next()
    8. })

    2.main.js引入router/premit
    image.png

    token登录流程
    image.png
    1.新建utils/app.js

    1. import cookie from "cookie_js"
    2. export function getToken(){
    3. return cookie.get("admin_token")
    4. }

    2.路由守卫新增getToken逻辑,router/premit.js

    import router from "@/router/index";
    import {getToken} from "@/utils/app";
    
    //白名單
    const whiteRouter = ['/login']; //indexOf方法,判断数组中是否存在指定的对象. 如果不存在,则返回-1
    
    //路由守卫
    router.beforeEach((to, from, next) => {
    
        if(getToken()){
            //路由动态添加,分配菜单,每个角色分配不通的菜单
            console.log("存在token")
        }else{
            console.log("不存在token")
            // next("/login")
            if(whiteRouter.indexOf(to.path) !==-1 ){
                next();
            }else{
                next('/login')  //路由指向
            }
        }
        /* 
        1. 直接进入index的时候,参数to被改变了"/index",触发路由指向,就会跑beforeEach
        2. 再一次next指向login,再次发生路由指向,再跑beforeEach,这个to的path参数改变成了login
        3. 进入白名单,判断存在,则直接执行next(),因为没有参数,所以不会再次beforeEach
        */
    
        // console.log(to) //进入的页面(下一个页面)
        // console.log(from) //离开之前的页面
        // console.log(next)
        // next()
    })
    

    这样的话实现了,访问任何一个页面,只要没有cookie里面没有token,就会跳转登录页面。