Vue+element使用table实现树形菜单

使用一维数组现实树形菜单,根据菜单的层级使用动态样式缩进实现视觉上的层级效果






utils两个工具类

export function arrayToTree(list, props = {id: 'id', pid: 'pid', children: 'children'}) {
  let tree = [];
  let map = {};
    debugger
  let listLength = list.length;
  for (let i = 0; i < listLength; i++) {
    let node = list[i];
    let nodeId = node[props.id];
    map[nodeId] = node;
  }

  for (let i = 0; i < listLength; i++) {
    let node = list[i];
    let nodePid = node[props.pid];
    let parentNode = map[nodePid];
    if (parentNode) {
      parentNode[props.children] = parentNode[props.children] || [];
      parentNode[props.children].push(node)
    } else {
      tree.push(node)
    }
  }

  return tree
}

export function ergodicTree(tree, callback = () => {}, props = {id: 'id', pid: 'pid', children: 'children'}) {
  function _ergodicTree(tree, parentIdPath, depth = 0) {
    const treeLength = tree.length;
    for (let i = 0; i < treeLength; i++) {
      let node = tree[i];
      const _idPath = parentIdPath ? [...parentIdPath, node[props.id]] : [node[props.id]];
      const _depth = depth + 1;
      node._idPath = _idPath;
      node._depth = _depth;
      callback(node);
      if (node[props.children] && node[props.children] instanceof Array) {
        _ergodicTree(node[props.children], _idPath, _depth)
      }
    }
  }

  _ergodicTree(tree);
  return tree;
}

你可能感兴趣的:(Vue+element使用table实现树形菜单)