递归 一下 vue里 nodePathArray 需要在 data里定义 。然后在methods里加上 getNodeRoute 调用就是 this.getNodeRoute(xx,xx) 还是有就是 getNodeRoute 里的nodePathArray.push 改成 this.nodePathArray.push
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
const dataList = [
{
id: 1,
name: "广东省",
items: [
{
id: 11,
name: "深圳市",
items: [
{
id: 112,
name: "福田区",
items: [
{
id: 1121,
name: "福田区666",
items: [
]
},
]
},
]
},
]
},
];
// function lu(data,id){
// data.map((item)=>{
// })
// }
// 首先我们先定义个数组,用来保存路径节点id
let nodePathArray = []
// (tree为目标树,targetId为目标节点id)
function getNodeRoute(tree, targetId) {
for (let index = 0; index < tree.length; index++) {
if (tree[index].items) {
let endRecursiveLoop = getNodeRoute(tree[index].items, targetId)
if (endRecursiveLoop) {
nodePathArray.push(tree[index].name)
return true
}
}
if (tree[index].id === targetId) {
nodePathArray.push(tree[index].name)
return true
}
}
}
getNodeRoute(dataList, 1121) //查找id为112的节点路径
console.log(nodePathArray.reverse().join('-'));
</script>
</html>