如何处理三级或者更多级的树形菜单结构

一:后台返回的数据格式是下面这样的:

{
"code":5200,
"data":{
"permission":[
{"code":"shoppingMall","icon":null,"jump":null,"menuId":2,"name":"shoppingMall","orderNum":2,"parentId":0,"title":"商城","type":0},
{"code":"goodsManagement","icon":null,"jump":null,"menuId":4,"name":"goodsManagement","orderNum":1,"parentId":2,"title":"商品管理","type":1},
{"code":"normalGoods","icon":null,"jump":null,"menuId":7,"name":"normalGoods","orderNum":1,"parentId":4,"title":"普通商品","type":1},
{"code":"sellerGoods","icon":null,"jump":null,"menuId":8,"name":"sellerGoods","orderNum":2,"parentId":4,"title":"分销商品","type":1},
{"code":"dropGoods","icon":null,"jump":null,"menuId":9,"name":"dropGoods","orderNum":3,"parentId":4,"title":"下架商品","type":1}], "token":""}, "message":"Success !"}

主要是通过parentId来实现之间的父子关系

 

二:处理方法

function menu(data) {
  data.forEach((item, index) => {
    const hasIndex = data.findIndex((item2, index2) => {
      return item2.menuId === item.parentId
    })
    if (hasIndex > -1) { //如果把当前元素循环当前的menuid是别的的parentid就加一个children的属性,并把值放进来
      if (data[hasIndex].children) {
        data[hasIndex].children.push(item)
      } else {
        data[hasIndex].children = [item]
      }
      // data.splice(index, 1)
    }
  })
  var newMenu = data.filter(item => {
    return item.parentId === 0 //只返回根目录的菜单,里面已经包好了子菜单
  })
 
  return newMenu
}

三。处理完的格式

[
children:[
    {
....... //这里面再套children和上面结构一样
    }
]
code: "shoppingMall"
component: Object
icon: null
jump: null
menuId: 2
meta: Object
name: "shoppingMall"
orderNum: 2
parentId: 0
path: "/shoppingMall"
title: "商城"
type: 0
]        

 

posted @ 2019-05-07 18:47  missLiuliu  阅读(1084)  评论(0编辑  收藏  举报