历史搜索

vue el

游客2024-10-22 07:53:02
目录文章目录
  1. 方法一:最普通的写法
  2. 方法二:深搜(DFS)/递归
  3. 方法三:广搜(BFS)

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

vue el 1

这里一共总结了 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
标签:el-tree