......
data: () => ({
// 數據 dt: [{ id: '1', children: [ { id: '1-1', children: [ { id: '1-1-1', children: [] } ] }, { id: '1-2', children: [ { id: '1-2-1', children: [] } ] } ] }, { id: '2', children: [ { id: '2-1', children: [ { id: '2-1-1', children: [{ id: '2-1-1-1', children: [] }] } ] } ] }], path: [],// 保存遞歸到的每一層路徑 curPath: [], // 當前路徑 curId: '2-1-1', // 目標節點 isRecursion: true // 是否已找到目標幾點 }), methods: { handleTestClick () { const { dt } = this this.path = [] dt.forEach((item, index) => { this.path[index] = [item.id] // 將每一層的路徑保存下來 this.recursion(item.children, index) }) console.log(this.path, this.curPath) }, recursion (ary, index) { for (let i = 0; i < ary.length; i++) { const item = ary[i] this.isRecursion && this.path[index].push(item.id) // 將父節點id添加到當前層路徑 if (this.curId === ary[i].id) { this.curPath = this.path[index] // index層的路徑就是目標節點的路徑 this.isRecursion = false break } if (item.children && item.children.length && this.isRecursion) { this.recursion(item.children, index) } } } }
......
-- 經過地獄般的磨練,創造出天堂的力量。流過血的手指,彈出世間的絕唱!--
個人博客對應地址:http://www.devloper.top/article/detail/c8a20870-3329-11eb-8d80-e5b0e11d80e6