天天看点

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: [email protected]
 * @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