layui后台管理系统 - 权限树
下面是我的项目链接,喜欢的可以star一下:
基于springboot + layui 的后台管理系统
最近一直在使用layui做后台管理系统,但遇到一些bug,特此记录踩坑记录
1. 关于权限树,先上截图:

2.实现代码:
后端:
service
@Overridepublic List<TreeMenu> selectByAdminId(Integer id) {//获取用户所有的全部权限(父,子权限)菜单List<TreeMenu> treeMenuList = treeMenuMapper.selectByAdminId(id);//保存所有的父(主)菜单List<TreeMenu> root = new ArrayList<>();//遍历所有菜单集合,如果是主菜单的话直接放入root集合for(TreeMenu treeMenu : treeMenuList){//pid为0,则为父(主)菜单if(treeMenu.getPid() == -1){root.add(treeMenu);}}//这个是遍历所有主菜单,分别获取所有主菜单的所有子菜单for(TreeMenu treeMenu : root){//获取所有子菜单 递归List<TreeMenu> childrenList = getchildrenMeun(treeMenu.getId(),treeMenuList);//这个是实体类中的子菜单集合treeMenu.setChildren(childrenList);}return root;}//递归获取子菜单public List<TreeMenu> getchildrenMeun(int id,List<TreeMenu> allMeun){//用于保存子菜单List<TreeMenu> childrenList=new ArrayList<>();for (TreeMenu info: allMeun){//判断当前的菜单标识是否等于主菜单的idif(info.getPid()==id){//如果是的话 就放入主菜单对象的子菜单集合childrenList.add(info);}}//这里就是递归了,遍历所有的子菜单for (TreeMenu info:childrenList){info.setChildren(getchildrenMeun(info.getId(),allMeun));}//如果子菜单为空的话,那就说明某菜单下没有子菜单了,直接返回空,子菜单为空的话就不会继续//迭代了if(childrenList!=null && childrenList.size()==0){return null;}returnchildrenList;}
其中实体类为:
private Integer id;private Integer pid;private String name;private String icon;private String url;private Boolean checked = false;//添加元素private List<TreeMenu> children = new ArrayList<>();//get set 方法省略
直接将列表返回前端即可。
前端:
layui.use(['jquery','element'], function(){var $ = layui.jquery;var element = layui.element;$(function () {$.ajax({url:'/manager/treeMenu',dataType:'json',type:'post',success:function(data){//先添加所有的主菜单$.each(data,function(i,obj){var content='<li class="layui-nav-item">';content+='<a href="javascript:;"><i class="fa fa-fw '+ obj.icon+'"></i> '+obj.name+'</a>';//这里是添加所有的子菜单content+=loadchild(obj);content+='</li>';$(".layui-nav-tree").append(content);});element.init();}})})//组装子菜单的方法function loadchild(obj){if(obj==null){return;}var content='';if(obj.children!=null && obj.children.length>0){content+='<dl class="layui-nav-child">';}else{content+='<dl>';}if(obj.children!=null && obj.children.length>0){$.each(obj.children,function(i,note){if(note.url == "/manager/index"){content+='<dd>';content+='<a style="margin-left: 21px" href="'+ note.url+'">'+note.name+'</a>';}else{content+='<dd>';content+='<a style="margin-left: 21px" lay-href="'+ note.url+'">'+note.name+'</a>';}if(note.children==null){return;}content+=loadchild(note);content+='</dd>';});content+='</dl>';}return content;}});
最后就如上图显示。
注: 此方法也是我从CSDN上找到的,关于具体链接忘了,若原作者可找到我,立即改正附加链接。