el-tree的问题

请问一下el-tree树组件拖拽后有没有什么办法可以给每个节点重新赋值每个节点的顺序,由上向下,依次递增。因为后台需要传递树形数据,但是需要有一个sort值代表顺序。 或者有没有什么方法可以遍历一下整个树节点,给他们每个都加上sort?

阅读 1.4k
1 个回答

给你一个展平树的工具函数:

interface TreeOptions<T = string> {
  keyField?: T,
  childField?: T,
  parentField?: T,
  rootId?: any
}

function flatTree<T = any>(tree: T[], options: TreeOptions<keyof T> = {}) {
  const {
    keyField = 'id' as keyof T,
    childField = 'children' as keyof T,
    parentField = 'parent' as keyof T,
    rootId = null
  } = options

  const hasRootId = isDefined(rootId) && rootId !== ''
  const list: T[] = []
  const loop = [...tree]

  let idCount = 1

  while (loop.length) {
    const item = loop.shift()!

    let id
    let children: any[] = []

    const childrenValue = item[childField]

    if (Array.isArray(childrenValue) && childrenValue.length) {
      children = childrenValue
    }

    if (item[keyField]) {
      id = item[keyField]
    } else {
      id = idCount++
    }

    if (hasRootId ? item[parentField] === rootId : !item[parentField]) {
      (item as any)[parentField] = rootId
    }

    for (let i = 0, len = children.length; i < len; ++i) {
      const child = children[i]

      child[parentField] = id
      loop.push(child)
    }

    list.push(item)
  }

  return list
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题