遍历菜单数组,获取选中的子节点的所有父节点元素

  1. 假设有一个数组如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    let menus = [
    {
    key: "menu1",
    label: "一级菜单1",
    icon: "",
    },
    {
    key: "menu2",
    label: "一级菜单2",
    icon: "",
    },
    {
    key: "menu3",
    label: "一级菜单3",
    icon: "",
    children: [
    {
    key: "menu3_1",
    label: "一级菜单3_1",
    icon: "",
    children: [
    {
    key: "menu3_1_1",
    label: "一级菜单3_1_1",
    icon: "",
    },
    ],
    },
    {
    key: "menu3_2",
    label: "一级菜单3_2",
    icon: "",
    },
    ],
    },
    {
    key: "menu4",
    label: "未开发页面演示",
    icon: "",
    },
    ];
  2. 需要获取到选中菜单 menu3_1_1 的所有父元素,即 menu3,menu3_1 和 menu3_1_1,js 代码如下:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    /**
    * selectMenus 切换菜单时候触发的事件,参数为更改的菜单 key
    * breadCrumb 选中菜单的所有父元素的数组集
    */
    let breadCrumb = [];
    // 遍历菜单
    function eachMenus(item, name) {
    for (let i = 0, j = item.length; i < j; i++) {
    breadCrumb.push(item[i].label);
    if (item[i].children) {
    eachMenus(item[i].children, name);
    } else {
    if (item[i].key === name) {
    return;
    } else {
    breadCrumb.splice(this.breadCrumb.length - 1, 1);
    }
    }
    }
    breadCrumb.splice(this.breadCrumb.length - 1, 1);
    }

    function selectMenus(name) {
    breadCrumb = [];
    eachMenus(menus, name);
    }