1.路由设置
在router文件下的index.js文件中,加上meta。
如在这段代码中,访问login就需要role0或者role1的权限。
{
path: '/',
name: 'login',
component: Login,
meta:{
authority: ["role0","role1"],
},
},
2.检查
在main.js中添加如下代码,判断是否登录、是否有权限
/*路由守卫*/
export function check(authority = []){
let current = window.sessionStorage.getItem("role");//getCurrentAuthority();
//console.log('authority.includes(current):'+authority.includes(current));
return authority.includes(current);//current.some(item=>item.includes(item))
}
export function isLogin(){
const token= window.sessionStorage.getItem("token");
return token!=null;
}
import findLast from "lodash/findLast";
router.beforeEach((to,from,next)=>{
// findLast: 找到临近当前对象的authority
const record = findLast(to.matched, record =>record.meta.authority)
if(record && !check(record.meta.authority)){
if(!isLogin() && to.path !== '/login'){
next({
path:"/login"
})
}else if(to.path !=="403"){
next({
path:"/403"
})
}
}
next();
})