eltree 树形结构数据转换

后端返回的数据格式

 转成el-tree接收的格式

 // 树形结构数据转换 每个元素的 children 属性对应的 value 通过 pid 去找到,然后递归执行下去
    arrToTree(arr, upperDeptId = '0') {
      const res = []
      arr.forEach(item => {
        if (item.upperDeptId == upperDeptId) {
          const children = this.arrToTree(arr.filter(v => v.upperDeptId !== upperDeptId), item.id)
          if (children.length) {
            res.push({ ...item, children })
          } else {
            res.push({ ...item })
          }
        }
      })
      return res
    },
    getDeptList({ pageIndex: 1, pageSize: 1000, upperDeptId: '' }).then(res => {
        const list = res.data.list
        this.departmentList = this.arrToTree(list, '0')
 
        // 默认高亮第一个节点
        this.$nextTick(() => {
          this.$refs.deptTree.setCurrentKey(list[0].id)
        })
 
      })
 

 转换后的数据格式

原文地址:https://www.cnblogs.com/lemonmoney/p/15813895.html