将pid进行上下级关联的数据转换成element-ui需要的children嵌套的函数
// 列表转树形结构
export function listToTree(arr, id) {
// arr:原始数组,id部门的id
const list = []
// 处理的过程
// 循环数据,获取数组中对象的pid和传入的id进行比较,如果相等则说明该部门是id的子部门
// (如果id值为空字符串 说明该部门为一级部门)
arr.forEach(item => {
if (item.pid === id) {
list.push(item)
// 根据二级部门的pid和一级部门的id来找父子部门关系
// 如果二级部门的pid和一级部门的id,则表示该二级部门为一级部门的子部门
// item已经确定了是一级部门
// item里面原来是没有children属性的,我们需要给他添加上去
// 怎么添加呢?答:item.children 只要这些写上去就表示给item添加children属性了
// item.children = [] // 因为需要用到数组的方法,因此使用children之前必须给children初始值为空数组
// arr.forEach(val => {
// if (val.pid === item.id) {
// item.children.push(val)
// }
// })
item.children = listToTree(arr, item.id)
}
})
// return 处理后的树形结构数据
return list
}