不包含children属性的一段数组对象,前端转化成包含children的树结构数据展示
实现效果
每点击一次列表数据,根据点击行id查询对应下级数据列表,找到点击的列表下标,将其children数据进行赋值
数据格式
[
{
“id”: “b25e633484564c76804906015e8719f8”,
“name”: “荆门市”,
“isParent”: true,
“open”: false,
“attributes”: {
“code”: “ORGAN_1042246615965896704”,
“hasElement”: true,
“status”: “1”
},
“pid”: “b58721a3-4a4c-4d28-acb3-800910834ae1”
}
]
代码
<el-cascader
v-model="infoform.areaCode"
placeholder="请选择所属区域"
:options="areaList"
:props="{
checkStrictly: true,
emitPath: false,
value: 'id',
label: 'name',
}"
ref="refHandle"
clearable
:show-all-levels="false"
filterable
@expand-change="handleExpand"
@change="handleAreaChange"
></el-cascader>
// 递归
iterateChildren(arr, val, responseData) {
let index = arr.map((e) => e.id).indexOf(val);
if (index == -1) {
arr.forEach((item) => {
if (item.children && item.children.length) {
index = item.children.map((e) => e.id).indexOf(val);
if (index == -1) {
// 该对应展开项无子集时
this.iterateChildren(item.children, val, responseData);
} else {
// 该对应展开项有子集时
this.$set(item.children, [index], {
...item.children[index],
children: responseData,
});
if (!responseData || !responseData.length) {
// 没有子属性时
// 删除children属性
delete item.children[index].children;
}
}
}
});
} else {
this.$set(arr, [index], {
...arr[index],
children: responseData,
});
}
},
// 级联-展开
handleExpand(val) {
let param = { id: val[val.length - 1] };
areaList(param).then((res) => {
if (res.code == "200") {
if (res.data && res.data.length) {
res.data.forEach((e) => {
e.children = [];
});
}
this.iterateChildren(this.areaList, val[val.length - 1], res.data);
}
});
},
// 级联-变化
handleAreaChange(val) {
if (val && val.length) {
this.infoform.areaCode = [val];
this.areaCode = val;
}
}