router.beforeEach(async(to, from, next) => {
// 进度条开始
NProgress.start()
// 确认用户是否已登录(获取它的token值,这里的getToken()是封装好的一个方法)
const hasToken = getToken()
if (hasToken) {//如果有token,说明是登录状态
if (to.path === '/login') {//路由是/login页,那么直接跳转到首页
next({ path: '/' })
NProgress.done() //进度条结束
} else {//如果不是登录页
// 确定用户是否已通过getInfo获得其权限角色
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {//如果通过角色权限,继续访问
next()
} else {//如果没有通过角色权限
// alert('没有role')
console.log('获取角色')
try {
// get user info
// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
const { roles } = await store.dispatch('user/getInfo')
// generate accessible routes map based on roles
const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
// dynamically add accessible routes
router.addRoutes(accessRoutes)
// hack method to ensure that addRoutes is complete
// set the replace: true, so the navigation will not leave a history record
next({ ...to, replace: true })
} catch (error) {
// remove token and go to login page to re-login
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {//如果没有token
/* has no token*/
// alert('没有token to.path=' + to.path)
if (whiteList.indexOf(to.path) !== -1) {//白名单中有的路由,可以继续访问
// in the free login whitelist, go directly
next()
} else {//否则,白名单中没有的路由,跳回首页
// other pages that do not have permission to access are redirected to the login page.
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})