一次性渲将数据整合成组件树所需的格式并完成渲染

考虑到for循环多层嵌套的执行效率过低,所以现在从节点的最里层开始一层一层向外赋值这样可以避免循环嵌套超过三层,执行速度也不会很慢 。
下面是js 代码 (项目使用的是vue框架)

 appRequest.getAllTree(paramss,header).then(data => {//请求获取所有节点
      _this.ztree=data;
      let gjd=0;
      let j=0,m=0,n=0,k=0,a=0,i=0;
      for(i=0;i<data.length;i++){//加载根节点
        if(_this.node==data[i].domain){//_this.node 代表当前用户所在的根节点的ID
          var tree_json1 = [{
            id:data[i].domain,//当前节点
            label: data[i].name,//节点名称
            isLast: false,
            level: parseInt(data[i].nodetype),//节点类型
            parentId: data[i].parent,//父节点ID
            children:[]
          }];
          gjd=data[i].nodetype;
          _this.data=tree_json1
        }
      }
      let childtrees=_this.data[0].children;
      let oneth=[],twoth=[],threeth=[],fourth=[],fiveth=[];
      for(i=0;i<_this.ztree.length;i++){//将请求回来的数据处理成页面渲染需要的格式 并按嵌套的层级分类存储在不同的数组内
        let tree_json1 = {
          id:_this.ztree[i].domain,//当前节点
          label:_this.ztree[i].name,//节点名称
          isLast: false,
          level: parseInt(_this.ztree[i].nodetype),//节点类型
          parentId: _this.ztree[i].parent,//父节点ID
          children:[]
        };
        if(_this.ztree[i].nodetype==(gjd+1)){
          oneth.push(tree_json1);
        } else if(_this.ztree[i].nodetype==(gjd+2)){
          twoth.push(tree_json1);
        } else if(_this.ztree[i].nodetype==(gjd+3)){
          threeth.push(tree_json1);
        } else if(_this.ztree[i].nodetype==(gjd+4)){
          fourth.push(tree_json1);
        } else if(_this.ztree[i].nodetype==(gjd+5)){
          fiveth.push(tree_json1);
        }
      }
      _this.data[0].children=_this.setTrees(_this.setTrees(_this.setTrees( _this.setTrees(fiveth,fourth),threeth),twoth),oneth) ;
    }).catch(err => {console.log(err)});

下面是setTree函数

setTrees(child_obj,parent_obj){
  let i=0,j=0;
  if(child_obj.length!=0){//从最里层开始向外循环,把最里层的子对象赋值给父对象
    for(i=0;i<parent_obj.length;i++){
      for(j=0;j<child_obj.length;j++){
        if(parent_obj[i].id==child_obj[j].parentId){
         parent_obj[i].children.push(child_obj[j])
        }
      }
    }
 }
 return parent_obj;
},

最终的页面效果如下图
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐