nispgithub.github.io

角色列表

添加“选择菜单”按钮

 <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    <el-button size="small" type="warning" @click="handlePermission(scope.$index, scope.row)">分配权限</el-button>
                    <el-button size="small" type="success" @click="handleMenu(scope.$index, scope.row)">选择菜单</el-button>
                </template>

添加选择菜单对话框

设置策略 check-strictly=”true”

 <!-- 选择菜单 -->
      <el-dialog v-model="menuVisible" title="选择菜单" @close="dialogClose">
            <el-form :model="roles.menu">
                <el-form-item label="角色名称" :label-width="formLabelWidth">
                    
                </el-form-item>
                <el-form-item label="菜单" :label-width="formLabelWidth">
                    <el-tree
                        ref="treeRef"
                        :data="roles.menuTree"
                        show-checkbox
                        node-key="id"
                        check-strictly="true"
                        :default-checked-keys="roles.menu.menuIds"
                        :props="defaultProps"
                    />
                </el-form-item>
                <el-input type="hidden" v-model="roles.menu.id" autocomplete="off" />
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="menuVisible = false">取消</el-button>
                    <el-button type="primary" @click="roleMenuSubmit">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

js

import { menuApi } from '@/api/menuApi'

const treeRef = ref()
const defaultProps = {
  children: 'children',
  label: 'menuName',
}
const menuVisible = ref(false);
const roles = reactive({
    role:{
    id:'',
    roleName: '',
    roleCode: '',
    },
    roleEdit:{
    id:'',
    roleName: '',
    roleCode: '',
    },
    permissions:{
    id:'',
    roleName: '',
    roleCode: '',
    perIds:[]
    },
    menu:{
    id:'',
    roleName: '',
    roleCode: '',
    menuIds:[]
    },
    permissionList:[],
    menuTree:[{
    id: 2,
    label: 'Level one 2',
    children: [
      {
        id: 5,
        label: 'Level two 2-1',
      },
      {
        id: 6,
        label: 'Level two 2-2',
      },
    ],
  }]
}
    )
    
     //选择菜单显示
 const handleMenu = (index, row) => {
    menuVisible.value = true;
    roles.menu = row;

}
//选择菜单提交
function roleMenuSubmit() {
    //获取选择的菜单ids
    roles.menu.menuIds = treeRef.value.getCheckedKeys();
    roleApi.addMenu(roles.menu).then(res => {
        //处理返回值
        if (res.code == 200) {
            //关闭弹窗
            menuVisible.value = false;
        } else {
            ElMessage.error(res.msg);
        }
        //刷新列表
        getListPage();
    })

}
//关闭窗口修改 关闭时清除树的选中状态
//关闭弹窗
function dialogClose(){
     //刷新列表
     getListPage();
     //清除树的选中状态
     treeRef.value?.setCheckedKeys([])
}

roleApi

添加选择菜单的提交方法

 addMenu(menus){
        return instance.post('/rbac/role/addMenu', menus).then(res => res.data);
    },

后台接口(类比添加权限相关接口)

查询分页列表中返回数据添加菜单的ID数组

Role实体添加字段

 @TableField(exist = false)
    private Set<Integer> menuIds = new HashSet<>();

RoleServiceImpl中的listPage添加menuIds

 @Override
    public IPage<Role> listPage(Integer page, Integer limit, Role role) throws Exception {
        //参数校验
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        //查询
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        if(role != null){
            //角色编码
            if(StringUtils.hasText(role.getRoleCode())){
                queryWrapper.like(Role::getRoleCode,role.getRoleCode());
            }
            //角色名称
            if(StringUtils.hasText(role.getRoleName())){
                queryWrapper.like(Role::getRoleName,role.getRoleName());
            }
        }

        IPage<Role> iPage =  roleMapper.selectPage(new Page<>(page,limit),queryWrapper);
        //角色关联权限
        if(iPage.getRecords().size() > 0) {
            for (int i = 0; i < iPage.getRecords().size(); i++) {
                Role roleRecord = iPage.getRecords().get(i);
                //根据角色id查询权限列表
                QueryWrapper<RolePermission> qw = new QueryWrapper<>();
                qw.lambda().eq(RolePermission::getRoleId,roleRecord.getId());
                List<RolePermission> list = rolePermissionMapper.selectList(qw);
                if(list != null && list.size() > 0){
                    //赋值权限ids
                    roleRecord.setPerIds(list.stream().map(RolePermission::getPermissionId).collect(Collectors.toSet()));
                }
                //根据角色id查询菜单列表
                QueryWrapper<RoleMenu> qwMenu = new QueryWrapper<>();
                qwMenu.lambda().eq(RoleMenu::getRoleId,roleRecord.getId());
                List<RoleMenu> menuList = roleMenuMapper.selectList(qwMenu);
                if(menuList != null && menuList.size() > 0){
                    //赋值菜单ids
                    roleRecord.setMenuIds(menuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toSet()));
                }
            }
        }
        return iPage;
    }

添加选择菜单提交的接口

 controller控制层
 /*
     * 新增选择菜单
     * */
    @PostMapping("/addMenu")
//    @PreAuthorize("hasAuthority('ADMIN:ADD')")
    public ResponseBean addMenu(@RequestBody Role role){
        try{
            return ResponseBean.ok(roleService.addMenu(role));
        }catch (Exception e){
            //e.printStackTrace();
            log.error("PermissionController--addMenu====>");
            log.error(e.getMessage());
            return ResponseBean.failed(e.getMessage());
        }
    }
    
 
 
    
 Iservice接口层
 
    int addMenu(Role role) throws Exception;
    
    
 RoleServiceImpl逻辑实现层
    @Override
    public int addMenu(Role role) throws Exception {
        if(role.getId() == null){
            throw new Exception("主键不能为空");
        }
        //查询角色的相关权限
        QueryWrapper<RoleMenu> qw = new QueryWrapper<>();
        qw.lambda().eq(RoleMenu::getRoleId,role.getId());
        List<RoleMenu> roleMenuList = roleMenuMapper.selectList(qw);
        if(roleMenuList != null && roleMenuList.size() > 0){
            //有相关菜单
            //角色的所有菜单删除
            roleMenuMapper.delete(qw);

        }
        //获取菜单ids
        Set<Integer> menuIds = role.getMenuIds();
        if(menuIds != null && menuIds.size() > 0) {
            //遍历菜单信息
            for (Integer menuId : menuIds) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(role.getId());
                roleMenu.setMenuId(menuId);
                //插入角色关联菜单
                roleMenuMapper.insert(roleMenu);
            }
        }
        return 1;
    }
    

主页获取当前用户菜单

HomeView.vue

//获取用户菜单信息
getUserMenus();
function getUserMenus(){
  instance.get('/rbac/user/userMenus').then(res =>{
    if(res.data.code == 200){
      //成功 保存菜单信息
      data.menus = res.data.res;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

后台接口(类比获取权限接口)

/*
     * 查询登录用户菜单信息
     * */
    @GetMapping("/userMenus")
    public ResponseBean userMenus(Principal principal){
        try {
            return ResponseBean.ok(userService.userMenus(principal.getName()));
        }catch (Exception e){
            log.error("UserController--userMenus:" + e.getMessage());
            return ResponseBean.failed(e.getMessage());
        }
    }
List userMenus(String username)  throws Exception;
 @Override
    public List userMenus(String username) throws Exception {
        List result = new ArrayList<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername,username).eq(User::getStatus,0);
        User user = userMapper.selectOne(queryWrapper);
        QueryWrapper<RoleUser> qw = new QueryWrapper<>();
        qw.lambda().eq(RoleUser::getUserId,user.getId());
        List<RoleUser> roleUserList = roleUserMapper.selectList(qw);
        if(roleUserList != null && roleUserList.size()>0){
            //角色id 集合
            Set<Integer> ids = roleUserList.stream().map(RoleUser::getRoleId).collect(Collectors.toSet());
            //#role 角色信息
//        select * from role where id in (1);
            QueryWrapper<Role> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(Role::getId,ids);
            Set<Role> roleSet = new HashSet<>(roleMapper.selectList(wrapper));
            //权限 角色下的所有权限ids  查询权限表  set到角色中(permissionSet)
            if(roleSet.size()>0) {
                for(Role role : roleSet){
                    //角色关联菜单 根据角色id
                    QueryWrapper<RoleMenu> menuQueryWrapper = new QueryWrapper<>();
                    menuQueryWrapper.lambda().eq(RoleMenu::getRoleId, role.getId());
                    Set<RoleMenu> roleMenuSet = new HashSet<>(roleMenuMapper.selectList(menuQueryWrapper));
                    //当前角色下所有菜单ids
                    Set<Integer> idsMenu = roleMenuSet.stream().map(RoleMenu::getMenuId).collect(Collectors.toSet());
                    if(idsMenu.size() > 0) {
                        //角色下所有菜单信息
                        QueryWrapper<Menu> qwMenu = new QueryWrapper<>();
                        qwMenu.lambda().in(Menu::getId, idsMenu);
                        List<Menu> all = menuMapper.selectList(qwMenu);
                        //一级菜单
                        List<Menu> first = all.stream().filter(i->i.getParentId().equals(0)).collect(Collectors.toList());
                        if(first.size() > 0){
                            for(Menu menu : first){
                                //二级菜单
                                menu.setChildren(all.stream().filter(i->i.getParentId().equals(menu.getId())).collect(Collectors.toList()));
                            }
                        }
                        //添加菜单到返回值
                        result.addAll(first);
                    }
                }
            }
        }
        return result;
    }