该项目git地址
- 结合项目源码更容易看懂 代码更完整
思路
-
我是按照动态路由的模式来生成的 menu
- 所以我在 mockjs 中的 数据定义如下
-
const menu = mock([ { id: 38, name: () => Random.name(), type: 1, url: '/main/analysis', icon: 'el-icon-monitor', sort: 1, children: [ { id: 39, name: '你的故事', type: 2, url: '/main/analysis/overview', icon: 'el-icon-monitor', sort: 5, children: null, parentId: 38, }, { id: 40, name: '核心技术', type: 2, url: '/main/analysis/dashboard', icon: 'el-icon-monitor', sort: 13, children: null, parentId: 38, }, { id: 41, name: '职业技术', type: 2, url: '/main/analysis/dashboard', icon: 'el-icon-monitor', sort: 14, children: null, parentId: 38, }, ], }, { id: 42, name: () => Random.name(), type: 1, url: '/main/story', icon: 'el-icon-chat-line-round', sort: 4, children: [ { id: 43, name: '你的物品', type: 2, url: '/main/story/chat', icon: 'el-icon-monitor', sort: 2, children: null, parentId: 42, }, ], }, ])
-
然后找到 官网中的 menu 进行 for 循环遍历
-
这里有个小坑
- 就是我定义的是 数字类型 而官网要求的 :index="" 是 string
- 所以这里使用隐式要转换一下 item.id + ''
-
第二个坑
- 官网复制下来后 如果使用折叠效果的话 他的样式会乱
- 在外层加了 template 来使用 for 循环才可以
-
-
<template> <div class="nav-menu"> <div class="logo"> <img class="img" src="~@/assets/img/logo.svg" alt="logo" /> <span v-if="!collapse" class="title">Vue3+TS</span> </div> <!-- 这个有 bug --> <!-- <el-menu default-active="2" class="el-menu-vertical" mode="vertical" :collapse="props.collapse" background-color="#0c2135" text-color="#b7bdc3" active-text-color="#0a60bd" > <el-sub-menu v-for="item in userMenus" :key="item.id"> <template #title> <el-icon><location /></el-icon> <span>{{ item.name }}</span> </template> <el-menu-item-group v-for="subitem in item.children" :key="subitem.id"> <el-menu-item :index="subitem.id">{{ subitem.name }}</el-menu-item> </el-menu-item-group> </el-sub-menu> </el-menu> --> <el-menu default-active="2" class="el-menu-vertical" mode="vertical" :collapse="props.collapse" background-color="#0c2135" text-color="#b7bdc3" active-text-color="#0a60bd" > <template v-for="item in userMenus" :key="item.id + ''"> <el-sub-menu :index="item.id + ''"> <template #title> <el-icon><location /></el-icon> <span>{{ item.name }}</span> </template> <template v-for="subitem in item.children" :key="subitem.id + ''"> <el-menu-item :index="subitem.id + ''" @click="handleMenuItemClick(subitem)" >{{ subitem.name }}</el-menu-item > </template> </el-sub-menu> </template> </el-menu> </div> </template>
\