1.使用
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const route = new Router()
2.路由守卫
// 路由白名单
const whiteList = ['/login']
// 路由前置守卫
router.beforeEach((to, from, next) => {
// 路由跳转的进度条开始(如果需要)
NProgress.start()
// 判断token
if (getToken()) {
// 有token,且跳转的目标页面为login时,将其跳转到首页,结束进度条
if (to.path === '/login') {
next({ path: '/' })
NProgress.done()
} else {
// 跳转的页面不是login页面,判断获取用户权限数据的接口是否调用完毕,这里数据是存在仓库里的
if (store.getters.roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息
store.dispatch('GetInfo').then(res => {
// 拉取user_info
const roles = res.roles
store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
// 根据roles权限生成可访问的路由表
router.addRoutes(accessRoutes) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
})
})
.catch(err => {
// 接口有问题则退出系统
store.dispatch('FedLogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else {
next()
// 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
// if (hasPermission(store.getters.roles, to.meta.roles)) {
// next()
// } else {
// next({ path: '/401', replace: true, query: { noGoBack: true }})
// }
// 可删 ↑
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next()
} else {
// 没有token且不在白名单直接进入登录页
next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
NProgress.done()
}
}
})
// 路由后置守卫,路由跳转后关闭加载进度条
router.afterEach(() => {
NProgress.done()
})