0
点赞
收藏
分享

微信扫一扫

vue限制访问的方式

阎小妍 2022-05-26 阅读 46

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();
})
举报

相关推荐

0 条评论