个人常用的就两种, 一个 全局守卫 一个独享路由守卫
1.全局守卫
适合项目url不多 或 角色权限不多
在router文件夹的index.js文件里
const router = new VueRouter({
//base: '/trade',
routes
})
let roleList = [{
name: '计划管理专员',
list: ['/plan/allPlan']
}, {
name: '采购经办员',
list: ['/purchaseTransactions/serverTrading', '/purchaseTransactions/goodsTrading']
}]
router.beforeEach(async (to, from, next) => {
// next()
// TODO 无登录 目前不做拦截
if (to.path == '/login' || to.path == '/register') {
next()
} else {
if (!localStorage.getItem('token')) {
next('/login')
} else {
if (JSON.parse(localStorage.getItem('userInfo')).roleNames.split(',').indexOf('主体管理员') >= 0) {
//最高权限不做限制
base.setVuexResourceMenu(to.path)
next()
} else {
//我这里是一个人可以有多个角色所以需要split做urlList去重合并
let nowRoleList = JSON.parse(localStorage.getItem('userInfo')).roleNames.split(',')
let permissionsUrlList = ['/info/personInfo']//不受角色限制的url放入这里,比如个人信息,404等
nowRoleList.forEach((element) => {
roleList.some((item) => {
if (item.name == element) {
permissionsUrlList = [...item.list, ...permissionsUrlList] //合并
permissionsUrlList = [...new Set(permissionsUrlList)] //去重
//去重合并后permissionsUrlList 里面就都是我当前角色可进入的跳转的url
}
})
});
if (permissionsUrlList.indexOf(to.path) >= 0) {//这里判断的是我要跳转的页面是否在我角色可进入的页面
base.setVuexResourceMenu(to.path)
next()
} else {
next('/info/personInfo')
}
}
}
}
})
2.路由独享守卫
适合url需要做判断的很多且是多人开发
{
path: '/purchaseTransactions/goodsTrading',
component: () =>
import('@/views/purchaseTransactions/goodsTrading.vue' /* */ ),
beforeEnter: (to, from, next) => {
//直接判断允许哪些角色跳转,不允许的跳转至个人信息或其他公共页
if (JSON.parse(localStorage.getItem('userInfo')).roleNames.split(',').indexOf('主体管理员') >= 0 || JSON.parse(localStorage.getItem('userInfo')).roleNames.split(',').indexOf('采购经办员') >= 0) {
next()
} else {
next('/info/personInfo')
}
}
},