Vue-router beforeEach登录鉴权(二)

137 阅读1分钟

前言

之前也写过一般比较简单的,随着需求的不断增加,简单的有些不适用,因此进行改写。

src根目录下新建permission.js

import router from './router'
//存放不需要登录即可访问的path
const whiteList = ['/login','/404','/errorTip',...];
//获取token判断是否已登录,自行修改参数
let hasToken = localStorage.getItem('token');
const routeBefore = (to, callBack) => {
    //跳转前可进行的操作,如设置网页标题
    if (to.meta && to.meta.title) {
        document.title = to.meta.title
    }
    callBack(to)
}

router.beforeEach(async (to, from, next) => routeBefore(to, () => {
    if (hasToken) {
        if (to.path === '/login') {
            //如果已经登录跳转到首页
            next({
                path: '/'
            })
        } else {
            next()
        }
    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            //未登录在白名单中的path直接进行跳转
            next()
        } else {
            if (可进行额外的跳转判断,跳转的path需要包含在whiteList中) {
                next('/errorTip')
            } else {
                next({ name: 'login' })
                // next(`/login?redirect=${to.fullPath}`)
            }
        }
    }
}))

main.js中进行引用

import '@/permission'