树表格做懒加载-点击小箭头走接口
children为[]则使用hasChildren的true/false来判断是否有子节点,另,如果要做懒加载必须加lazy及load
<el-tablev-if="refreshTable"v-loading="loading":data="deptList"lazy:load="load"row-key="deptId":default-expand-all="isExpandAll":tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
load(tree, treeNode, resolve) {this.queryParams.deptId = tree.deptId;this.loading = true;// 假设你有一个 API 方法来获取子节点数据queryDeptByParentId(this.queryParams) // 这里的 deptId 是当前节点的标识符.then((response) => {resolve(response.data);this.loading = false;}).catch((error) => {console.error("加载子节点失败:", error);this.loading = false;resolve([]); // 如果加载失败,返回空数组});},
/** 查询部门列表 */getList() {this.loading = true;this.queryParams.deptId = null;this.deptList = null;listDept(this.queryParams).then((response) => {this.deptList = this.handleTree(response.data, "deptId");this.deptList.forEach((item) => {this.initializeChildren(item);});this.loading = false;});},// 递归函数,用来确保每个节点的 children 字段是一个数组initializeChildren(item) {// 如果有子节点但没有 children 字段,则初始化为一个空数组if (item.hasChildren && !Array.isArray(item.children)) {item.children = [];}// 如果当前节点有 children,并且 children 是数组,则递归处理每个子节点if (Array.isArray(item.children)) {item.children.forEach((child) => {this.initializeChildren(child); // 递归处理子节点});}},/*** 构造树型结构数据* @param {*} data 数据源* @param {*} id id字段 默认 'id'* @param {*} parentId 父节点字段 默认 'parentId'* @param {*} children 孩子节点字段 默认 'children'*/
export function handleTree(data, id, parentId, children) {let config = {id: id || 'id',parentId: parentId || 'parentId',childrenList: children || 'children'};var childrenListMap = {};var nodeIds = {};var tree = [];for (let d of data) {let parentId = d[config.parentId];if (childrenListMap[parentId] == null) {childrenListMap[parentId] = [];}nodeIds[d[config.id]] = d;childrenListMap[parentId].push(d);}for (let d of data) {let parentId = d[config.parentId];if (nodeIds[parentId] == null) {tree.push(d);}}for (let t of tree) {adaptToChildrenList(t);}function adaptToChildrenList(o) {if (childrenListMap[o[config.id]] !== null) {o[config.childrenList] = childrenListMap[o[config.id]];}if (o[config.childrenList]) {for (let c of o[config.childrenList]) {adaptToChildrenList(c);}}}return tree;
}