异步加载树结构

前端:

 $scope.init = function () {

                    //一次性加载树
                    //$scope.getTree();
                    //懒加载树
                    $scope.getTreeAsync('');
                }

$scope.initTree = function (result) {
                    if ($scope.LeftTree == null) {
                        $scope.LeftTree = result;
                    }
                    layui.use(['tree', 'util'], function () {
                        $scope.tree = layui.tree
                            , layer = layui.layer
                            , util = layui.util
                            , beforeTreeId = ''
                        $scope.tree.render({
                            elem: '#test13'
                            ,id:'test13'
                            , data: $scope.LeftTree
                            , accordion: true
                            , onlyTextControl:true
                            //, data: data1
                            //, id: 'Name'
                            , showLine: false  //是否开启连接线
                            , click: function (obj) {
                                $scope.currTree = obj.data;
                                var currTreeId = obj.data.id; //当前点击的树节点
                                beforeTreeId = $('#tree_id').val() == '' ? beforeTreeId : $('#tree_id').val(); //上一次点击的树节点id
                                //对比前后id,不相同时移除上一个节点的样式,并设置当前点击的节点样式
                                if (currTreeId != beforeTreeId) {
                                    $('div [data-id="' + currTreeId + '"] div').eq(0).last().css('background-color', '#EEEEEE');
                                    $('div [data-id="' + beforeTreeId + '"] div').eq(0).last().css('background-color', '');
                                    $('#tree_id').val(obj.data.id);
                                }
                                if (obj.state == 'close') {
                                    $scope.getTreeAsync(obj.data.code);
                                }
                                //显示右边详情信息
                                $scope.showDetail(obj.data.id);
                            }
                        });
                    });
                }

                $scope.getTreeAsync = function (UpperCode) {
                    var layindex = layer.load(0, { shade: [0.2, '#000'] });//0.2透明度的黑色背景
                    $.post('@Url.Action("FileDirectoryMain_list", "Configuration")', { UpperCode: UpperCode}, function (data) {
                        layer.close(layindex);
                        if (data.ResultCode == '1') {
                            let result = JSON.parse(json_obj(data.LeftTreeList));
                            if (UpperCode == '') {
                                $scope.initTree(result);
                            }
                            else {
                                let curNode = getCurNode($scope.LeftTree, $scope.currTree.id);
                                curNode.children = result;
                                curNode.spread = true;
                                // 重载
                                $scope.tree.reload('test13', { // options
                                    data: $scope.LeftTree
                                });
                            }
                        }
                    });
                }

$scope.getTree = function () {
                    $.post('@Url.Action("FileDirectoryMain_tree", "Configuration")', { }, function (data) {
                        if (data.ResultCode == '1') {
                            scope.LeftTree = JSON.parse(json_obj(data.LeftTreeList));
                            layui.use(['tree', 'util'], function () {
                                var tree = layui.tree
                                    , layer = layui.layer
                                    , util = layui.util
                                    , beforeTreeId = ''
                                tree.render({
                                    elem: '#test13'
                                    , data: $scope.LeftTree
                                    , accordion: true
                                    //, data: data1
                                    //, id: 'Name'
                                    , showLine: false  //是否开启连接线
                                    , click: function (obj) {
                                        console.log(obj.data); //得到当前点击的节点数据
                                        console.log(obj.state); //得到当前节点的展开状态:open、close、normal
                                        console.log(obj.elem); //得到当前节点元素

                                        console.log(obj.data.children); //当前节点下是否有子节点

                                        var currTreeId = obj.data.id; //当前点击的树节点
                                        beforeTreeId = $('#tree_id').val() == '' ? beforeTreeId : $('#tree_id').val(); //上一次点击的树节点id
                                        //对比前后id,不相同时移除上一个节点的样式,并设置当前点击的节点样式
                                        if (currTreeId != beforeTreeId) {
                                            $('div [data-id="' + currTreeId + '"] div').eq(0).last().css('background-color', '#EEEEEE');
                                            $('div [data-id="' + beforeTreeId + '"] div').eq(0).last().css('background-color', '');
                                            $('#tree_id').val(obj.data.id);
                                        }
                                        //显示右边详情信息
                                        $scope.showDetail(obj.data.id);
                                    }
                                });
                            });
                        }
                    });
                }

后台

[Description("电子文件目录 初始化树")]
        [PFAuthorize, HttpPost]
        public JsonResult FileDirectoryMain_list(string UpperCode)
        {
            try
            {
                List<ElectronicDocumentCatalogEntity> allList= ElectronicDocumentCatalog.GetByCondition("Status=1 order by Sort");

                List<ElectronicDocumentCatalogEntity> list = null;
                if (string.IsNullOrEmpty(UpperCode))
                    list = allList.Where(a => string.IsNullOrEmpty(a.Uppercode)).OrderBy(a => a.Sort).ToList();
                else
                    list = allList.Where(a => a.Uppercode == UpperCode).OrderBy(a => a.Sort).ToList();

                List<Dnode> nodeList = new List<Dnode>();
                if (list != null && list.Count > 0)
                {
                    foreach (ElectronicDocumentCatalogEntity item in list)
                    {
                        Dnode node = new Dnode();
                        node.id = item.Id.ToString();
                        node.code = item.Code;
                        node.title = item.Name;
                        node.spread = false;
                        var children = allList.Where(a => a.Uppercode == item.Code).OrderBy(a=>a.Sort).ToList();
                        if (children != null && children.Count() > 0)
                        {
                            List<Dnode> childNodeList = new List<Dnode>();
                            foreach (var child in children)
                            {
                                Dnode childNode = new Dnode();
                                childNode.id = child.Id.ToString();
                                childNode.code = child.Code;
                                childNode.title = child.Name;
                                childNode.spread = false;
                                childNodeList.Add(childNode);
                            }
                            node.children = childNodeList;
                        }
                        
                        nodeList.Add(node);
                    }
                }
                return Json(new
                {
                    ResultCode = "1",
                    LeftTreeList = JsonHelper.ListToJson(nodeList),
                });

            }
            catch (Exception ex)
            {
                PFPageHelper.LogException(CurrentModuleId, ex);
                return Json(new { ResultCode = "0", ResultMessage = "获取数据失败!" });
            }
        }

[Description("电子文件目录 初始化树")]
        [PFAuthorize, HttpPost]
        public JsonResult FileDirectoryMain_tree()
        {
            try
            {
                List<Dnode> treedata = ElectronicDocumentCatalog.GetElectronicDocumentCatalogTree();

                return Json(new
                {
                    ResultCode = "1",
                    LeftTreeList = JsonHelper.ListToJson(treedata),
                });

            }
            catch (Exception ex)
            {
                PFPageHelper.LogException(CurrentModuleId, ex);
                return Json(new { ResultCode = "0", ResultMessage = "获取数据失败!" });
            }
        }

        /// <summary>
        /// 获取电子文件目录树
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static List<Dnode> GetElectronicDocumentCatalogTree()
        {
            List<Dnode> tree = new List<Dnode>();

            List<ElectronicDocumentCatalogEntity> alllist = ElectronicDocumentCatalogDA.GetByCondition("Status=1 Order By Sort");
            foreach (ElectronicDocumentCatalogEntity item in alllist.Where(a => string.IsNullOrEmpty(a.Uppercode)))
            {
                Dnode rootNode = new Dnode();
                rootNode.id = item.Id.ToString();
                rootNode.code = item.Code;
                rootNode.title = item.Name;
                rootNode.path.Add(rootNode.code);
                GetChildren(rootNode, alllist);
                tree.Add(rootNode);
            }
            void GetChildren(Dnode nodel, List<ElectronicDocumentCatalogEntity> list)
            {
                var children = list.Where(a => a.Uppercode == nodel.code);
                if (children != null && children.Count() > 0)
                {
                    nodel.children = new List<Dnode>();
                    foreach (ElectronicDocumentCatalogEntity item in children)
                    {
                        Dnode childNode = new Dnode();
                        childNode.id = item.Id.ToString();
                        childNode.code = item.Code;
                        childNode.title = item.Name;
                        childNode.path.AddRange(nodel.path);
                        childNode.path.Add(childNode.code);
                        GetChildren(childNode, list);
                        nodel.children.Add(childNode);
                    }
                }
            }
            return tree;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以参考下面这个示例,在 React 中使用 Ant Design 的 TreeSelect 组件实现异步加载树结构: ```jsx import React, { useState, useEffect } from 'react'; import { TreeSelect } from 'antd'; const { TreeNode } = TreeSelect; // 模拟异步加载数据 const loadData = async (id) => { return new Promise((resolve) => { setTimeout(() => { resolve([ { id: `${id}-1`, title: `Leaf ${id}-1` }, { id: `${id}-2`, title: `Leaf ${id}-2` }, ]); }, 1000); }); }; const AsyncTreeSelect = () => { const [treeData, setTreeData] = useState([]); useEffect(() => { // 初始化根节点数据 loadData('root').then((data) => { setTreeData(data); }); }, []); const handleLoadData = async (treeNode) => { const { id } = treeNode.props; const data = await loadData(id); treeNode.props.dataRef.children = data; setTreeData([...treeData]); }; const renderTreeNodes = (data) => { return data.map((item) => { if (item.children) { return ( <TreeNode title={item.title} key={item.id} id={item.id} dataRef={item}> {renderTreeNodes(item.children)} </TreeNode> ); } return <TreeNode title={item.title} key={item.id} id={item.id} dataRef={item} isLeaf />; }); }; return ( <TreeSelect style={{ width: '100%' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} placeholder="请选择" loadData={handleLoadData} > {renderTreeNodes(treeData)} </TreeSelect> ); }; export default AsyncTreeSelect; ``` 在上面的代码中,loadData 函数模拟异步加载数据的过程,可以根据实际情况进行修改。组件初始化时,会调用 loadData 函数加载根节点数据,并将其存储在 state 中。当用户点击某个节点时,会根据该节点的 id 异步加载子节点数据,并更新该节点的 children 属性,最后更新 state,从而触发 TreeSelect 的重新渲染。通过递归方式渲染所有的节点,并将 dataRef 属性设置为节点数据,方便后续操作。最后将节点组件作为 TreeSelect 的子组件,即可生成异步加载树结构

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值