直接上代码
html部分
<el-form-item label="部门" prop="deptId">
<el-cascader v-model="addForm.deptId" :props="props" size="small"></el-cascader>
</el-form-item>
js部分
props: {
lazy: true,
value: "code",
label: "name",
children: "children",
lazyLoad: (node, resolve) => {
const { level = 0, data = {}, value = '' } = node;
if (level === 0) {
upData.code = 23;
} else {
const { type = 0, deptRegionCode = '' } = data || {};
if (type === 1) {
upData.code = deptRegionCode;
upData.type = type;
} else {
upData.code = value;
}
}
api.userList.getTreeData(upData).then(res => {
const { code = 0, data = {} } = res;
if (code === 200) {
const { departmentList = [], regionList = [] } = data || {};
let departmentListData = this.handleTree(
departmentList,
"code",
"deptRegionCode",
);
let regionListData = this.handleTree(
regionList,
"code",
"parentCode",
);
let children = departmentListData.concat(regionListData);
resolve(children);
}
});
}
},
handleTree 函数
export function handleTree(data, id, parentId, children) {
if (Array.isArray(data)) {
let config = {
id: id || "id",
parentId: parentId || "parentId",
childrenList: children || "children",
};
var childrenListMap = {};
var nodeIds = {};
var tree = [];
for (let d of data) {
d.ordinal = Number(d.ordinal)
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) {
d.ordinal = Number(d.ordinal)
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;
} else {
return [];
}
}
本代码得到的是数组结构的值