1.例:从后端接口中获得的扁平数据
let treeList = [
{
id: 1,
name: '一年级',
parentId: 0,
parentName: '学校'
},
{
id: 2,
name: '二年级',
parentId: 0,
parentName: '学校'
},
{
id: 3,
name: '一年级一班',
parentId: 1,
parentName: '一年级'
},
{
id: 4,
name: '一年级一班第一小组',
parentId: 3,
parentName: '一年级一班'
},
]
2.数组转为树形结构
// 数组转为树形结构
arrayToTree (items) {
const result = []; // 存放结果集
const itemMap = {};
for (const item of items) {
const id = item.id;
const pid = item.parentId;
if (!itemMap[id]) {
itemMap[id] = {
children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {
result.push(treeItem);
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: [],
}
}
itemMap[pid].children.push(treeItem);
}
}
return result;
},
3.上面处理完后我们会发现最后一级叶子节点有一个空的children空属性,在实际级联选择器中会显示无数据,所以需要对这一问题进行处理
// 处理叶子节点
isChildrenNull(arr) {
return arr.map(item => {
if (item.children.length > 0) {
this.isChildrenNull(item.children)
} else {
delete item.children
}
return item;
})
},
4.同时我们注意到官方文档中的需要的是value和label,但是我们拿到的数据是id和name,所以我们还需修改节点属性的名称
// 修改属性名称,构造级联选择器数据结构
changeObjaryKey(objAry, key, newkey) {
objAry.forEach(item => {
// 新增替换的属性的键值
Object.assign(item, {
[newkey]: item[key]
})
// 去掉旧属性键值
delete item[key]
this.changeObjaryKey(item.children, key, newkey)
});
},
5.代码调用示例如下:
<el-cascader
v-model="addForm.parentCpId"
:options="optionList"
:show-all-levels="false"
placeholder="请选择"
style="width: 2.6rem">
</el-cascader>
let optionList = this.arrayToTree(treeList);
this.changeObjaryKey(optionList, 'id', 'value');
this.changeObjaryKey(optionList, 'name', 'label');
this.isChildrenNull(optionList);