vue 树节点递归获取父节点 id

思路:
首先,递归循环tree节点的所有节点;
然后创建一个map类型去接,set所有节点的id对属性名,递归循环节点就把父对象id去赋值子节点的id;
所有tree树形数据结构,就会有parentID,id,没有父节点可以默认赋值parentID=0。

import MenuData from 'xxx公共方法'
const treeList = {
    'code': '1',
    'text': '公司1',
    'leaf': false,
    'children': [
      {
        'code': '2',
        'text': '部门',
        'leaf': false,
        'children': [
          {
            'code': '3',
            'text': '小组1',
            'leaf': true,
            'children': null
          },
          {
            'code': '4',
            'text': '小组2',
            'leaf': true,
            'children': null
          }
        ]
      },
      {
        'code': '5',
        'text': '公司2',
        'leaf': false,
        'children': [
          {
            'code': '6',
            'text': '简称',
            'leaf': true,
            'children': null
          }
        ]
      }
    ]
  }
 const treeMenu = new MenuData(treeList, 'code')
 // 获取tree的parentId
 const parent = treeMenu.getParent(node.code)

公共方法:

class MenuData {
  menuMap = new Map();
  menus = [];
  codeName = ''
  constructor(data, code) {
    this.codeName = code || 'id'
    this.init(data)
  }

  init(data) {
    data.forEach(item => {
      item.parentId = '0'
      this.deepSetItem(item)
    })
  }
  
  deepSetItem(item) {
    this.menuMap.set(item[this.codeName], item)
    this.menus.push(item)
    if (item.children) {
      item.children.forEach(menuItem => {
        menuItem.parentId = item[[this.codeName]] // item[[this.codeName]]是父节点的 id,  menuItem.parentId是当前节点 id
        this.deepSetItem(menuItem)
      })
    }
  }

  getMenuById(id) {
    return this.menuMap.get(id)
  }

  getChildern(id) {
    return this.menuMap.get(id).children
  }

  getParent(id) {
    const item = this.getMenuById(id)
    const parent = this.getMenuById(item.parentId)
    return parent
  }
}

export default MenuData

你可能感兴趣的:(vue.js,javascript,前端)