el-tree的问题
请问一下el-tree树组件拖拽后有没有什么办法可以给每个节点重新赋值每个节点的顺序,由上向下,依次递增。因为后台需要传递树形数据,但是需要有一个sort值代表顺序。 或者有没有什么方法可以遍历一下整个树节点,给他们每个都加上sort?
回答:
给你一个展平树的工具函数:
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
}
以上是 el-tree的问题 的全部内容, 来源链接: utcz.com/p/937537.html