1.
在首次请求登录接口的时候,由后端返回相应的角色权限,再根据这个进行动态路由生成。
自己根据角色创建不同的路由表,然后在登录时拿 到不同的角色标记,来引入对应的路由表。
2.把路由表存储在vuex中,右侧菜单通过直接引入vuex存的路由表进行渲染。
通过接口返回的角色权限,根据角色来动态的通过router.addRoutes(),添加不同的路由。
3.在路由守卫router.beforeEach中进行判断
const hasRoles = store.getters.roles && store.getters.roles.length > 0
if (hasRoles) {
next()
} else {
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()
}
}
原文:https://www.cnblogs.com/ygyy/p/14956949.html