js如何構造elementUI樹狀菜單的數據結構詳解
elementUI中自帶樹狀菜單,就是數據結構有點復雜,偏向json風格。
數據庫中菜單數據是二維表格,通過parentPk定義上下級,是list型。
需要把list轉換成tree的結構。
elementUI樹狀菜單的數據結構每個節點有4個屬性,id、label、newVal、children數組;
通過children數組包含關系標示上下級。
var treeData={id: 1,label: ’一級 1’,newVal: '',children: [{ id: 4, label: ’二級 1-1’, newVal: '', children: [{ id: 9, label: ’三級 1-1-1’, newVal: '', }, { id: 10, label: ’三級 1-1-2’, newVal: '', children:[{ id: 4444, label: ’四級 1-1-1-4’, newVal: '', }] }]},{ id:22, label:’二級 22’, newVal:’’}] }
數據庫返回的list
var itemlist =[{itemCode:’11’, itemName:’材料11’,itemType:’2’,parentPk:’1’},{itemCode:’111’, itemName:’材料111’,itemType:’3’,parentPk:’11’}, {itemCode:’1111’, itemName:’材料1111’,itemType:’3’,parentPk:’111’},{itemCode:’1112’, itemName:’材料1112’,itemType:’3’,parentPk:’111’} ]設計思路
用遞歸方法;
從list中遍歷,找parentPk是當前節點的id的對象,組裝成node,放到當前節點的children數組;同時,把list的對象刪除。 對新的node,遞歸執行找子節點的過程。 退出條件:list為空或者循環list完畢。 具體代碼//root節點全局對象,因為不同的遞歸執行,要訪問的一個tree對象var itemtree ={ id:’1’, label:’物料名稱_整機’, children:[]}//數據庫返回的菜單list全局對象,因為不同的遞歸執行,要訪問的一個list對象var itemlist =[{itemCode:’11’, itemName:’材料11’,itemType:’2’,parentPk:’1’},{itemCode:’12’, itemName:’材料12’,itemType:’2’,parentPk:’1’},{itemCode:’111’, itemName:’材料111’,itemType:’3’,parentPk:’11’}, {itemCode:’1111’, itemName:’材料1111’,itemType:’3’,parentPk:’111’},{itemCode:’1112’, itemName:’材料1112’,itemType:’3’,parentPk:’111’} ]function buildtree(itemtreenode,itemlist){ if (itemlist.length===0) { console.log(’條件結束’) return } var j=0 /*!!注意循環變量j必須定義為局部變量,否則默認全局變量,會導致子節點丟失*/// var len=0 for(j=0,len=itemlist.length;j<len;j++){ console.log(new Date(),’j==>:’,j,’len==>:’,len,itemtreenode,itemlist) if (itemtreenode.id===itemlist[j].parentPk){ var node={id:itemlist[j].itemCode,label:itemlist[j].itemName,children:[]} itemtreenode.children.push(node) // itemlist.splice(j,1) /*!! 沒有刪除list元素,否則會導致后續引用錯誤。代碼不是很完美,一時沒想到完美方法*/ buildtree(node,itemlist)} } console.log(’循環結束’)}console.log(’begin’)buildtree(itemtree,itemlist) console.log(itemtree)代碼執行結果
可以看到組裝樹是正確的。
總結ps:和設計方案對比,代碼不是很完美,list中被引用的元素沒有成功移除;移除后,后邊會報錯。暫時沒找到好方法,對性能有點影響。
樹data轉list代碼
與此相反的操作。
var treeData={id: 1,label: ’一級 1’,newVal: '',children: [{ id: 4, label: ’二級 1-1’, newVal: '', children: [{ id: 9, label: ’三級 1-1-1’, newVal: '', }, { id: 10, label: ’三級 1-1-2’, newVal: '', children:[{ id: 4444, label: ’四級 1-1-1-4’, newVal: '', }] }]},{ id:22, label:’二級 22’, newVal:’’, children:[{id:’2-2-1’,label:’三級221’,newVal:’’,children:[],}]}] }var exp=undefinedvar itemlist=[]function tree2list(itemnode){ if(typeof(itemnode)=='undefined'){ console.log(’返回:’,itemnode) return } if(itemnode.children && itemnode.children.length>0){ var i=0 for(i=0;i<itemnode.children.length;i++){ itemnode.children[i].parentPk=itemnode.id console.log(itemnode.children[i]) itemlist.push(itemnode.children[i]) this.tree2list(itemnode.children[i]) } }} console.log(’begin’)tree2list(treeData,itemlist)console.log(itemlist)
到此這篇關于js如何構造elementUI樹狀菜單的數據結構的文章就介紹到這了,更多相關js構造elementUI樹狀菜單內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: