vue 通过角色控制菜单拥有、访问权限

  • 版本vue 2.6
  • 路由硬编码配置,或者从关系数据库获取元数据再拼成下述结构
{
    path: '/monitors',
    component: Layout,
    redirect: '/monitors',
    children: [
      {
        path: 'monitors',
        component: () => import('@/views/monitors/index'),
        name: 'Monitors',
        meta: {
          roles: ['admin'],
          title: '监控',
          icon: 'monitor'
        }
      }
    ]
  },
  • 清洗路由 在后端接口被调用之前
/**
 * 功能描述: 静态路由-权限处理 根据用户角色筛选静态路由 角色配置于静态路由里
 * @param:
 * @return:
 * @mail: 8416837@qq.com
 * @author: cc
 * @date:  20:52
 */
function washConstantRoutes(constantRoutesNew) {
  constantRoutesNew.forEach((item, index) => {
    if (item && item.children && item.children) {
      item.children.forEach(routes => {
        if (routes.meta && routes.meta.roles) {
          console.log(`静态路由的角色依次是:`, routes.meta.roles)
          const currentUserRole = getCurrentUserRole()
          if (currentUserRole && currentUserRole.length > 0) {
            for (let i = 0; i < currentUserRole.length; i++) {
              if (!routes.meta.roles.includes(currentUserRole[i])) { // !当前静态路由允许该角色访问
                // 删除该路由
                console.log(`无权限,移除这个路由,结果:`, constantRoutesNew.splice(index, 1))
                break
              }
            }
          }
        }else {
          console.warn(`该静态路由没有设置meta或角色:`, item.path)
        }
      })
    }else {
      console.warn(`该静态路由没有设置子节点:`, item.path)
    }
  })
}
  • 设置路由,执行上述逻辑↑ 函数:washConstantRoutes
const permission = {
... ...
mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      // 初始化静态路由
      let rts = []
      constantRoutes.forEach(item => {
        rts.push(item)
      })
      washConstantRoutes(rts)
      state.routes = rts.concat(routes)
    }
  },
  ... ...
export default permission
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值