先声明每个角色都要有一个代表这个角色的标识(在登录时由后端返回)话不多说直接上代码
router.beforeEach(async (to, from, next) => {
if (!sessionStorage.getItem('userinfo')) {
localStorage.clear("token");
}
NProgress.start()
const hasToken = getToken()
if (hasToken) {
if (to.path === '/login') {
next()
NProgress.done()
} else {
const hasGetUserInfo = store.getters
if (hasGetUserInfo) {
if (JSON.parse(sessionStorage.getItem("userinfo")).role === 0) {
router.options.routes[5].children[2].hidden = true;
router.options.routes[7].hidden = true;
next()
}
if (JSON.parse(sessionStorage.getItem("userinfo")).role != 2) {
router.options.routes[6].children[3].hidden = true;
next()
}
next()
} else {
try {
await store.dispatch('user')
next()
} catch (error) {
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
if (whiteList.indexOf(to.path) !== -1) {
next()
} else {
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})