有时候树形结构需要确定某一项它的具体路径(它的所有父级节点),为提高效率和减少代码,可以在树结构的遍历时确定路径path操作,以下代码就实现了此功能(注意:此代码确定path路径是在meta对象中的那个):
treeUtils.js assembleTree方法二选一
path设置为数组方式
// 2022-08-30更新加入pathKey
export function assembleTree (nodes, parent, depth, pathKey) {
if (!depth) depth = 0
if (!pathKey) pathKey = 'id'
nodes.forEach(n => {
const path = parent.length ? parent.concat(n[pathKey]) : [n[pathKey]] // 数组记录path
n.meta = { name: n.name, role: n[pathKey], path: path, depth }
if (n.children && n.children instanceof Array) {
assembleTree(n.children, path, depth + 1, pathKey)
}
})
if (depth === 0) {
return nodes
}
}
// 使用案例 assembleTree(this.treeData, [], 0, 'id')
path设置为#号拼接方式
export function assembleTree(nodes, parent, depth) { if(!depth) depth = 0 nodes.forEach(n => { let path = parent?parent+'#'+n.path:n.path // 拼接path n.meta = {title: n.title, role: n.path, path: path} if (n.children && n.children instanceof Array) { assembleTree(n.children, path, depth) } }) if (depth === 0) { return nodes } depth++ }
测试数据
[ {title: 'a', path: 'a', children: [{title: 'a1', path: 'a1'}, {title: 'a2', path: 'a2'}]}, {title: 'c', path: 'c'}, ]
测试结果
[{"title":"a","path":"a","children":[{"title":"a1","path":"a1","meta":{"title":"a1","role":"a1","path":"a#a1"}},{"title":"a2","path":"a2","meta":{"title":"a2","role":"a2","path":"a#a2"}}],"meta":{"title":"a","role":"a","path":"a"}},{"title":"c","path":"c","meta":{"title":"c","role":"c","path":"c"}}]
对你有帮助就点个赞