案例1:树结构treeData,找到与this.activeData.id匹配的节点
this.nodeClickData=this.getNodeClickData(this.treeData)
getNodeClickData(val){
for(const item of val){
if(item.id==this.activeData.id){
console.log('匹配的节点==',item)
return item //找到之后,就返回
}
// 如果没有找到,就看看this.treeData有没有子级
let childResult=null
if(item.childrenKey && item.childrenKey.length>0){
childResult=this.getNodeClickData(item.childrenKey)
}
if(childResult){
return childResult //子级找到结果,就返回
}
}
return null
}
案例2: 找到选中节点的父级节点
// this.nodeClickData---选中的数据
const expandedKeys=this.getParentkeys(this.nodeClickData,this.treeData)
/*
* targetNode---选中节点
* treeData --- 树全部数据
*/
getParentkeys(targetNode,treeData,parentKeys=[]){
for(cosnt node of treeData){
if(node.id==targetNode.id){
return [...parentKeys,node.id]
}
// 没找到,如果有子级,就遍历子级
if(node.childrenKey && node.childrenKey.length>0){
const keys=this.getParentkeys(targetNode,node.childrenKey,[...parentKeys,node.id])
if(keys){
return keys
}
}
}
return null
}