当前位置: 首页 > article >正文

若依 ruoyi-vue 根据角色切换路由菜单权限 SAAS

在这里插入图片描述

后端根据角色查询相应的菜单(角色对应管理的系统)

    /**
     * 获取路由信息根据角色(系统类型)
     *
     * @return 路由信息
     */
    @GetMapping("getRoutersBySystemType")
    public AjaxResult getRoutersBySystemType(String systemType) {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.getRoutersBySystemType(userId, systemType);
        return AjaxResult.success(menuService.buildMenus(menus, null));
    }

    /**
     * 获取账号拥有的角色(系统类型)
     *
     * @return 系统类型
     */
    @GetMapping("getRouterSystemType")
    public AjaxResult getRouterSystemType() {
        Long userId = SecurityUtils.getUserId();
        List<String> routerSystemType = menuService.getRouterSystemType(userId);
        if (CollectionUtils.isEmpty(routerSystemType)) {
            return AjaxResult.error("请联系管理员分配账号权限");
        }
        return AjaxResult.success(routerSystemType);
    }
    @Override
    public List<SysMenu> getRoutersBySystemType(Long userId, String systemType) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll(null);
        } else {
            menus = menuMapper.selectMenuBySystemType(userId, systemType);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<String> getRouterSystemType(Long userId) {
        return menuMapper.selectMenuSystemTypeByUserId(userId);
    }

    <select id="selectMenuBySystemType" resultType="com.huida.common.core.domain.entity.SysMenu">
        select distinct m.menu_id,
        m.parent_id,
        m.menu_name,
        m.path,
        m.component,
        m.query,
        m.visible,
        m.status,
        ifnull(m.perms,'') as perms,
        m.is_frame,
        m.is_cache,
        m.menu_type,
        m.icon,
        m.order_num,
        m.create_time,
        m.mobile_share,
        m.mobile_component,
        m.mobile_path,
        m.mobile_icon
        from tz_sys_menu m
        left join tz_sys_role_menu rm on m.menu_id = rm.menu_id
        left join tz_sys_user_role ur on rm.role_id = ur.role_id
        left join tz_sys_role ro on ur.role_id = ro.role_id
        left join sys_users u on ur.user_id = u.id
        where u.id = #{userId}
        and (ro.manage_system = #{systemType} or ro.manage_system is null)
        and m.menu_type in ('M', 'C')
        and m.status = 0
        and ro.status = 0
        and (m.mobile_share is null or m.mobile_share in ('0', '1'))
        order by m.parent_id, m.order_num
    </select>

    <select id="selectMenuSystemTypeByUserId" resultType="java.lang.String">
        select distinct ro.manage_system
        from tz_sys_user_role ur
                 left join sys_users u on ur.user_id = u.id
                 left join tz_sys_role ro on ro.role_id = ur.role_id
        where u.id = #{userId}
          and ro.status = 0
          and ro.manage_system is not null
    </select>

前端点击切换按钮,切换相应菜单

// 获取路由根据角色(系统类型)
export const getRouterBySystemType = (systemType) => {
  return request({
    url: '/getRoutersBySystemType',
    method: 'get',
    params: {'systemType': systemType}
  })
}

// 获取账号拥有的角色(系统类型)
export const getRouterSystemType = () => {
  return request({
    url: '/getRouterSystemType',
    method: 'get',
  })
}

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes)
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({commit}) {
      return new Promise(resolve => {
        getRouterSystemType().then((response) => {
          getRouterBySystemType(response.data[0]).then((res) => {
            // 计算默认页面
            const defaultPage = calculateDefaultPage(res.data);
            // 缓存默认页面
            cache.session.set('defaultPage', defaultPage);

            const sdata = JSON.parse(JSON.stringify(res.data))
            const rdata = JSON.parse(JSON.stringify(res.data))
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            rewriteRoutes.push({path: '*', redirect: '/404', hidden: true})
            router.addRoutes(asyncRoutes)
            commit('SET_ROUTES', rewriteRoutes)
            commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            resolve(rewriteRoutes)
          }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
            })
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
          })
        })
      })
    },
    // 处理系统类型改变时的路由更新
    ChangeSystemRoutes({commit}, systemType) {
      return new Promise((resolve, reject) => {
        getRouterBySystemType(systemType)
          .then(res => {
            const sdata = JSON.parse(JSON.stringify(res.data))
            const rdata = JSON.parse(JSON.stringify(res.data))
            const sidebarRoutes = filterAsyncRouter(sdata)
            const rewriteRoutes = filterAsyncRouter(rdata, false, true)
            const asyncRoutes = filterDynamicRoutes(dynamicRoutes)
            rewriteRoutes.push({path: '*', redirect: '/404', hidden: true})
            router.addRoutes(asyncRoutes)
            commit('SET_ROUTES', rewriteRoutes)
            commit('SET_SIDEBAR_ROUTERS', constantRoutes.concat(sidebarRoutes))
            commit('SET_DEFAULT_ROUTES', sidebarRoutes)
            commit('SET_TOPBAR_ROUTES', sidebarRoutes)
            resolve(rewriteRoutes)
          })
          .catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
            })
          })
      })
    }
  }
}

    systemChange(e) {
      console.log('setSystemType', e)
      this.$store.dispatch("setSystemType", e)
       //关闭全部tab
      this.$tab.closeAllPage().then(() => {
        this.$tab.openPage("首页", "/index");
      })
      this.$store.dispatch('ChangeSystemRoutes', e).then(accessRoutes => {
        // 根据roles权限生成可访问的路由表
        router.addRoutes(accessRoutes) // 动态添加可访问路由表
        next({...to, replace: true}) // hack方法 确保addRoutes已完成
      })
      //获取代办事项
      initAgent().then(() => this.getList())
    },

http://www.kler.cn/a/563711.html

相关文章:

  • lowagie(itext)老版本手绘PDF,包含页码、水印、图片、复选框、复杂行列合并、行高设置等。
  • https:原理
  • DevOps全流程
  • 【红队利器】单文件一键结束火绒6.0
  • 【Python网络爬虫笔记】14-使用代理绕过访问限制
  • 生成GeoJson文件,Cesium@1.126.0中使用CZML,动态设置高度,动态设置颜色
  • 大语言模型(LLM)微调技术笔记
  • Android-创建mipmap-anydpi-v26的Logo
  • 【SpringMVC】十分钟跑起来一个SpringMVC项目
  • 逻辑函数的神经网络实现
  • DeepSeek-R1-Zero:基于基础模型的强化学习
  • Element UI日期选择器默认显示1970年解决方案
  • 生成SQL的模型与工具
  • 【LeetCode刷题记录】79. 单词搜索(JS解法)
  • 《机器学习数学基础》补充资料:从几何角度理解矩阵
  • Orcale、MySQL中左连接,右连接,内连接的区别以及运用场景系列04(运用场景、左右表关系)
  • 详解 c++ 中的 namespage
  • 算法-图-查找路径
  • 道可云人工智能每日资讯|深圳将设立人工智能和机器人产业基金
  • 【Android】ViewPager的使用