实现一个人员根据所在部门分类的el-cascader,使用人员表、部门表中数据,人员表中存有所在部门id字段,部门表中存有上级部门的id字段,人员为叶子节点,无子节点的部门不进行显示。
先遍历两个表,组合数据,对叶子节点进行标记。
that.personList.forEach(function(obj) {
that.personCascaderFront.push({
value: obj.id,
label: obj.name,
parentId: obj.deptid,
isLeaf: true
});
})
that.deptList.forEach(function(obj) {
that.personCascaderFront.push({
value: obj.id,
label: obj.simplename,
parentId: obj.pid
});
})
组合后的数据为
[
{
isLeaf: true
label: "管理员"
parentId: 2
value: 1
},
{
isLeaf: true
label: "网站管理员"
parentId: 3
value: 2
},
{
label: "总公司"
parentId: 0
value: 1
},
{
label: "开发部"
parentId: 1
value: 2
},
{
label: "战略部"
parentId: 1
value: 4
},
{
label: "智慧城管"
parentId: 2
value: 5
},
{
label: "新媒体"
parentId: 3
value: 6
}
]
调用方法 that.personCascader = that.generateOptions(that.personCascaderFront);
//生成Cascader级联数据
generateOptions(params) {
var that = this;
var result = [];
for (let param of params) {
if (param.parentId === 0) { //判断是否为顶层节点
var parent = { //转换成el-Cascader可以识别的数据结构
'label': param.label,
'value': param.isLeaf ? null : param.value
}
parent.children = that.getchilds(param.value, params); //获取子节点
console.log(parent.children)
result.push(parent);
}
}
return result;
},
//获取子节点
getchilds(id, array) {
var that = this;
let childs = new Array();
for (let arr of array) { //循环获取子节点
if (arr.parentId === id) {
childs.push({
'label': arr.label,
'value': arr.isLeaf ? null : arr.value
});
}
}
for (let i = 0; i < childs.length; i++) { //获取子节点的子节点
let childscopy = that.getchilds(childs[i].value, array); //递归获取子节点
if (childscopy.length > 0) {
childs[i].children = childscopy;
childs[i].haveChild = true;
} else { //去掉else,则生成所有节点
if (childs[i].haveChild === undefined && childs[i].value != null) {
childs.splice(i--, 1);
}
}
}
return childs;
},
输出结果为
[
{
label: "总公司",
value: 1,
children: [
{
haveChild: true,
label: "开发部",
value: 2,
children: [
{
label: "管理员",
value: null
}
]
},
{
haveChild: true,
label: "运营部",
value: 3,
children: [
{
label: "网站管理员",
value: null
}
]
}
]
}
]
参考https://blog.youkuaiyun.com/u013675978/article/details/90286757