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

目录
文章目录隐藏
  1. 方法一:最普通的写法
  2. 方法二:深搜(DFS)/递归
  3. 方法三:广搜(BFS)

最近项目用 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层级限制展示方法

发表回复