Ztree树的后端数据实现原理

Ztree树的后端数据实现原理

SpringBoot开发中用到的在Ztree树功能 前端框架为Xadmin和layui

效果展示

Ztree树的后端数据实现原理_第1张图片

前端代码


<html class="x-admin-sm" xmlns:th="http://www.thymeleaf.org">
    
    <head>
        <meta charset="UTF-8">
        <title>角色新增信息-豪哥码匠title>
        <hader th:replace="head::html">hader>
        <link rel="stylesheet"  th:href="@{/ztree/zTreeStyle/zTreeStyle.css}">
        <link rel="stylesheet"  th:href="@{/ztree/demo.css}">
    head>

    <body>
        <div class="x-body">
            <form class="layui-form">
                  <div class="layui-form-item">
                      <label for="L_name" class="layui-form-label">
                          <span class="x-red">*span>角色名
                      label>
                      <div class="layui-input-inline">
                          <input type="text" th:value="${role.name}" id="L_name" name="name" required="" lay-verify="required" autocomplete="off" class="layui-input">
                      div>
                      <div class="layui-form-mid layui-word-aux">
                          <span class="x-red">*span>将会成为角色名
                      div>
                  div>

                  <div class="layui-form-item">
                      <label for="L_description" class="layui-form-label">
                          <span class="x-red">*span>描述
                      label>
                      <div class="layui-input-inline">
                          <input type="text" th:value="${role.description}" id="L_description" name="description" required="" lay-verify="phone" autocomplete="off" class="layui-input">
                      div>
                      <div class="layui-form-mid layui-word-aux">
                          <span class="x-red">*span>该角色的定位或权限范围
                      div>
                  div>

                  <div class="layui-form-item">
                      <label class="col-md-2 control-label layui-form-label">权限label>
                      <div class="col-md-10 ">
                        <ul id="treeDemo" class="ztree">ul>
                      div>
                  div>

                  <div class="layui-form-item">
                      <button  class="layui-btn" lay-filter="add" lay-submit="">
                          增加
                      button>
                  div>
            form>
        div>
        <script>
            layui.use(['form', 'layer','laydate'],
            function() {
                $ = layui.jquery;
                var form = layui.form,
                layer = layui.layer,
                laydate=layui.laydate;



                //日期
                laydate.render({
                    elem:'#L_birthday'
                    ,format:'yyyy-MM-dd'
                });

                //自定义验证规则
                form.verify({
                   name:function (value){
                       if(value.length < 4){
                            return "角色名至少要四个字符";
                       }
                   }
                });

                //监听提交
                form.on('submit(add)',
                function(data) {
                    console.log(data);
                    var permissionIds = getCheckedMenuIds();//通过ztreeUtil中的getCheckedMenuIds方法来获取复选框是否选中
                    data.field.permissionIds = permissionIds;

                    $.ajax({
                        url: "/role/add",
                        type: "POST",
                        contentType:"application/json; charset=utf-8",
                        data:JSON.stringify(data.field),
                        dataType: 'json',
                        success:function (result) {
                           layer.alert("添加成功",{icon:6},function () {
                                //关闭当前frame
                               xadmin.close();
                               //可以对父窗口进行刷新
                               xadmin.father_reload();
                           });
                        }
                    });
                    return false;
                });
            });
            //初始化ztree树
        $.fn.zTree.init($("#treeDemo"),getSettting(),getMenuTree());
        script>
    body>

html>

通过初始化ztree树中的三个参数来构建ztree树,#treeDemo是用来放树的容器;getSettting()是用来判断复选框是否被选中,getMenuTree()则是用来通过数据库来遍历出树的具体内容

ztree树的工具js代码

//树形只包含菜单,不包含按钮
function onlyGetMenuTree() {
    var root = {
        id : 0,
        name : "root",
        open : true,
    };

    $.ajax({
        type : 'get',
        url : '/permission/listAllPermission',
        contentType : "application/json; charset=utf-8",
        async : false,
        success : function(ret) {
            var data = ret.data
            var length = data.length;
            var children = [];
            for (var i = 0; i < length; i++) {
                var d = data[i];
                var node = createNode(d,true);
                children[i] = node;
            }
			console.log(children);
            root.children = children;
        }
    });

    return root;
}
//获取的树形包括菜单和按钮
function getMenuTree() {
	var root = {
		id : 0,  //0为根节点
		name : "root",
		open : true,
	};

	$.ajax({
		type : 'get',
		url : '/permission/listAllPermission',
		contentType : "application/json; charset=utf-8",
		async : false, //非异步
		success : function(ret) {
			var data = ret.data
			var length = data.length;
			var children = [];
			for (var i = 0; i < length; i++) {
				var d = data[i];
				var node = createNode(d);
				children[i] = node;
			}

			root.children = children;
		}
	});

	return root;
}

function initMenuDatas(roleId){
    $.ajax({
        type : 'get',
        url : '/permission/listAllPermissionByRoleId?id=' + roleId,
        success : function(ret) {
            var data = ret.datas;
            var length = data.length;
            var ids = [];
            for(var i=0; i<length; i++){
                ids.push(data[i]['id']);
            }

            initMenuCheck(ids);
        }
    });
}

function initMenuCheck(ids) {
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var length = ids.length;
	if(length > 0){
		var node = treeObj.getNodeByParam("id", 0, null);
		treeObj.checkNode(node, true, false);
	}
	
	for(var i=0; i<length; i++){
		var node = treeObj.getNodeByParam("id", ids[i], null);
		treeObj.checkNode(node, true, false);
	}
	
}

function initRadioCheckTree(){
	var id = $("#parentId").attr("value");
	if(id != undefined && id.length > 0){
        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
        var node = treeObj.getNodeByParam("id", id, null);
        treeObj.checkNode(node, true, false);
	}
}
function initSelectType(){
    var type = $("#selectType").attr("value");
    if(type != undefined && type.length > 0){
        $("#selectType").siblings("div.layui-form-select").find('dl').find('dd[lay-value='+type+']').click()
    }
}
function getCheckedMenuIds(){
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var nodes = treeObj.getCheckedNodes(true);
	
	var length = nodes.length;
	var ids = [];
	for(var i=0; i<length; i++){
		var n = nodes[i];
		var id = n['id'];
		ids.push(id);
	}
	
	return ids;
}
//noShowBtn:树形列表中不显示按钮选择项,默认没值代表显示,true代表不显示
function createNode(d,noShowBtn) {

	var id = d['id'];
	var pId = d['parentId'];
	var name = d['name'];
	var child = d['child'];

	var node = {
		open : true,
		id : id,
		name : name,
		pId : pId,
	};

	if (child != null) {
		var length = child.length;
		if (length > 0) {
			var children = [];
			var j = 0;
			for (var i = 0; i < length; i++) {
                if(!(noShowBtn && child[i].type == 2)){
                    children[j] = createNode(child[i],noShowBtn);
                    j++;
                }
			}
			if(children.length > 0){
                node.children = children;
			}

		}

	}
	return node;
}

function initParentMenuSelect(){
	$.ajax({
        type : 'get',
        url : '/permissions/parents',
        async : false,
        success : function(data) {
            var select = $("#parentId");
            select.append("");
            for(var i=0; i<data.length; i++){
                var d = data[i];
                var id = d['id'];
                var name = d['name'];
                
                select.append(" +name+"");
            }
        }
    });
}

function getSettting(isRadioType){
	var setting = {
		check : {
			enable : true,
			chkboxType : {
				"Y" : "ps",
				"N" : "ps"
			}
		},
		async : {
			enable : true,
		},
		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "pId",
				rootPId : 0
			}
		},
		callback : {
			onCheck : zTreeOnCheck
		}
	};
	if(isRadioType){
        setting.check =  {
            enable: true,
			chkStyle: "radio",
			radioType: "all"
        }
	}
	return setting;
}

function zTreeOnCheck(event, treeId, treeNode) {
//	console.log(treeNode.id + ", " + treeNode.name + "," + treeNode.checked
//			+ "," + treeNode.pId);
//	console.log(JSON.stringify(treeNode));
}

getMenuTree()中通过 url : ‘/permission/listAllPermission’ 这个路劲来遍历 具体看以下代码

@Controller
@RequestMapping(value = "permission")
public class permissionController {
    @Autowired
    permissionService permissionService;

    @RequestMapping(value="/listAllPermission",method = RequestMethod.GET)
    @ResponseBody
    public result<JSONArray> listAllPermission(){
        return permissionService.listAllPermission();
    }
    //JSONArray 是通过阿里的fastjson工具来进行json数据的转换
pom.xml
		<dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.56version>
        dependency>
@Service
public class permissionServiceImpl implements permissionService {
    @Autowired
    permissionDao permissionDao;
    @Override
    public result<JSONArray> listAllPermission() {
        List datas = permissionDao.findAll();//获取所有的permission对象
        JSONArray array = new JSONArray();
        TreeUtils.setPermissionsTree(0,datas,array);//通过setPermissionsTree遍历出记录以及所对应的父目录
        return result.success(array);
    }
}

ztreeUtil.java
public static void setPermissionsTree(Integer parentId, List<permission> permissionsAll, JSONArray array) {
        for (permission per : permissionsAll) {
            if (per.getParentId().equals(parentId)) {
                String string = JSONObject.toJSONString(per);
                JSONObject parent = (JSONObject) JSONObject.parse(string);
                array.add(parent);
                //stream是jdk8的新特性可以用来遍历过滤
                if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
                    JSONArray child = new JSONArray();
                    parent.put("child", child);
                    setPermissionsTree(per.getId(), permissionsAll, child);//通过不断循环遍历直到最后
                }
            }
        }
    }

0代表根目录 第一个0对应id为1 ,1下面又有为2和6的对应,2下面又有id为3/4/5对应 也就是说 用户管理为根目录 下面的一级目录为用户查询和修改密码;用户查询下面又有二级目录为查询、新和删除
Ztree树的后端数据实现原理_第2张图片

你可能感兴趣的:(学习之旅,java,js,jquery)