引入組件
可以直接在項目中引入element-plus表格組件,如果需要變成下拉列表樣式需要添加以下屬性:
row-key 必填 最好給數字或唯一屬性 , 給每個節點設置id 不填的話 沒有辦法實現展開效果
load 這個是動態添加數據的 前提(開啟lazy ,表格數組里設置了hasChildren:true)
treeprops 是配置樹狀收縮數據的
treeprops :{hasChildren} 是否可收縮
treeprops :{children} 展開的子項
代碼示例:
<el-table:data="(所需要的渲染數據)"row-key="id"style="width: 100%; border: 0.1px solid #ebeef5"v-loading="loading"lazy:load="load":tree-props="{ hasChildren: 'hasChildren', children: 'children' }"//>
普通數組轉換成樹形數據
const transListDataToTreeData = (list, root) => {console.log(list);const arr = [];// 1.遍歷list.forEach(item => {// 2.首次傳入空字符串 判斷list的pid是否為0 如果為空就是一級節點if (item.pid === root) {// 找到之后就要去找item下面有沒有子節點 以 item.id 作為 父 id, 接著往下找const children = transListDataToTreeData(list, item.id);if (children.length > 0) {// 如果children的長度大于0,說明找到了子節點item.children = children;}// 將item項, 追加到arr數組中arr.push(item);console.log(arr);console.log(arr);}});return arr;};transListDataToTreeData(初始數組, "");