一、menu菜单分为三层结构

1.最外层el-menu标签

向第二层传递菜单结构数据
  1. <el-scrollbar>
  2. <el-menu :unique-opened="true" router>
  3. <SidebarItem
  4. :route="route"
  5. v-for="route in menuData"
  6. :key="route.path"
  7. ></SidebarItem>
  8. </el-menu>
  9. </el-scrollbar>

2.第二层el-menu-item

(1)判断是否包含子菜单

(2)有子菜单,调用自身进行循环递归渲染
  1. <el-menu-item :index="route.path" v-if="route.children.length === 0">
  2. <MenuItem :title="route.meta.title" :icon="route.meta.icon"></MenuItem>
  3. </el-menu-item>
  4. <el-submenu v-else :index="route.path">
  5. <template #title>
  6. <MenuItem :title="route.meta.title" :icon="route.meta.icon"></MenuItem>
  7. </template>
  8. <sideBarItem
  9. :route="child"
  10. v-for="child in route.children"
  11. :key="child.path"
  12. ></sideBarItem>
  13. </el-submenu>

3.最里层展示文字与图标

image.png

  1. <!-- element-plus图标 -->
  2. <i :class="icon" v-if="icon.includes('el-icon')" class="sub-el-icon"></i>
  3. <!-- element-plus图标 -->
  4. <svg-icon v-else :icon="icon"></svg-icon>
  5. <span>{{ title }}</span>

二、菜单收尾

1.动态css

创建一个store的getter,从getter获取动态css值,在template中使用store可以直接引用$store

2.路由跳转

给el-menu标签添加一个router属性

3.默认激活项

从vue-router中导入useRoute,获取path属性,赋值给el-menu的default-active属性

  1. <el-menu
  2. :unique-opened="true"
  3. :background-color="cssVariables.menuBg"
  4. :text-color="cssVariables.menuText"
  5. :active-text-color="cssVariables.menuActiveText"
  6. router
  7. :default-active="defualtMenu"
  8. >
  9. <SidebarItem
  10. :route="route"
  11. v-for="route in menuData"
  12. :key="route.path"
  13. ></SidebarItem>
  14. </el-menu>
  15. import { useRouter, useRoute } from 'vue-router'
  16. const route = useRoute()
  17. const defualtMenu = computed(() => {
  18. const { path } = route
  19. return path
  20. })