當前需求:層級列表中選中某個元素,則獲取最底層子集id,並用逗號鏈接(1,2,3,4,5);vue
let data = [{ id:"1", children:[{ id:"11", children:[{ id:"111", children:null }, { id:"112", children:null }, { id:"113", children:null }] }, { id:"12", children:[{ id:"121", children:null }, { id:"122", children:null }, { id:"123", children:null }] }] }];
遍歷方法可參考:https://blog.csdn.net/chaos_h...,寫的很詳細
具體操做:首先找到選擇元素的id在樹形數據中的位置,並獲取他bash
findSameId(tree, id) { let isGet = false; let retNode = null; function deepSearch(tree, id) { for (var i = 0; i < tree.length; i++) { if (tree[i].children && tree[i].children.length > 0) { deepSearch(tree[i].children, id); } if (id === tree[i].id || isGet) { isGet || (retNode = tree[i]); isGet = true; break; } } } deepSearch(tree, id); return retNode; };
找尋他的最底層子元素,也就是全部沒有子集的元素ide
findChildId(data) { console.log(data, 678); console.log(data.children, 678); if (data.children !== null) { for (let i = 0; i < data.children.length; i++) { console.log(data.children[i], i); const childrens = data.children[i]; if (childrens.hasOwnProperty("children") && childrens.children && childrens.children.length !== 0) { console.log('-------'); console.log(childrens, i); console.log('-------'); this.findChildId(childrens); } else { this.sideIds.push(childrens.id); } } } else { this.sideIds.push(data.id); } }
### 因爲自己是vue下的處理 handleSelectDept是觸發點擊獲取到對應id; this.sideIds是自己在data裏裏定義了的this
data(){ return{ sideIds:[] } }
handleSelectDept(key) { this.sideIds = [];//每次點擊須要把自己的sideIds清空 const dataId = this.findSameId(this.treeData, key); this.findChildId(dataId); console.log(this.sideIds, 9999) this.$set(this.queryForm, 'depIds', this.sideIds.join(",")); console.log(this.queryForm, 989); this.getTableData(); }