vue el-tree层级限制展示方法

最近项目用el-tree做一个组织结构树展示,产品要求只展示5层层级关系即可,这里不包括祖辈这一层。

vue el-tree层级限制展示方法

这里一共总结了3种实现方式。

方法一:最普通的写法

getOrgnizes().then((res) => {
  let arr = [];
  res.forEach((i) => {
    if (i.child && i.child.length) {
      i.child.forEach((j) => {
        if (j.child && j.child.length) {
          j.child.forEach((k) => {
            if (k.child && k.child.length) {
              k.child.forEach((l) => {
                if (l.child && l.child.length) {
                  l.child.forEach((m) => {
                    if (m.child && m.child.length) {
                      m.child.forEach((n) => {
                        if (n.child && n.child.length) {
                          // n.disabled = true;
                          delete n.child;
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    }
    arr.push(i);
  });
  this.treeData = arr;
});

但是这样虽然能实现效果,但是有点啰嗦,不灵活。

方法二:深搜(DFS)/递归

const limitLevel = (tree, level) => {
  if (!tree) return
  for (const node of tree) {
    if (level == 1) delete node.child
    else limitLevel(node.child, level - 1)
  }
}
// 利用可选链简写版
// const limitLevel = (tree, level) => tree?.forEach(node => {
//   if (level == 1) delete node.child
//   else limitLevel(node.child, level - 1)
// })

limitLevel(res, 5)
this.treeData = res

方法三:广搜(BFS)

const limitLevel = (tree, level) => {
  while (--level) tree = tree.flatMap(node => node.child || [])
  tree.forEach(node => delete node.child)
}

limitLevel(res, 5)
this.treeData = res

「点点赞赏,手留余香」

2

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:
本站所有文章教程及资源素材均来源于网络与用户分享或为本站原创,仅限用于学习和研究。
码云笔记 » vue el-tree层级限制展示方法

发表回复

IT互联网行业相关广告投放 更专业 更精准

立即查看 联系我们