问题描述:
递归方式根据子级id查询该子级的父级
解决方案:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>js递归遍历树结构</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<p> <span>{{list.join(' / ')}}</span></p>
</div>
<script>
new Vue({
el: '#app',
data: {
list: [],
treeList: [{
id: '1',
pid: null,
nm: '中国',
level: '1',
children: [{
id: '2-1',
pid: '1',
nm: '浙江省',
level: '2',
children: [{
id: '3-1',
pid: '2-1',
nm: '宁波市',
level: '3',
children: [{
id: '4-1',
pid: '3-1',
nm: '海曙区',
level: '4',
}, {
id: '4-2',
pid: '3-1',
nm: '鄞州区',
level: '4',
}]
}]
},
{
id: '2-2',
pid: '1',
nm: '江苏省',
level: '2',
children: [{
id: '3-2',
pid: '2-2',
nm: '南京市',
level: '3',
children: [{
id: '4-3',
pid: '3-2',
nm: '鼓楼区',
level: '4',
}, {
id: '4-4',
pid: '3-2',
nm: '玄武区',
level: '4',
}]
}]
},
]
}]
},
methods: {
use() {
this.seekParent(this.treeList, "4-2", this.treeList);
console.log(this.list);
},
// rootList为原始数据数组
seekParent(arr, aid, rootList) {
arr.forEach(e => {
if (e.id == aid) {
this.list.unshift(e.nm);
// 找到符合id后则获取该数据的父级id重新递归
this.seekParent(rootList, e.pid, rootList)
}
// 若没找到符合的id则继续递归
else {
if (e.children) {
this.seekParent(e.children, aid, rootList)
}
}
})
}
},
created() {
this.use();
}
})
</script>
</body>
</html>