使用el-menu和el-sub-menu及el-menu-item导航
src/layout目录下新增components目录,components目录下新增PageSidebar.vue
代码基本思想为:读取router中定义的routes数组,渲染绑定到el-menu。
el-menu和el-sub-menu及el-menu-item的区别,请参考本文最后一个图。
<template><div><el-menu :default-active="defaultActive" router :collapse="isCollapse"><template v-for="(item, i) in treeData" :key="item.path"><el-sub-menu :index="item.path" v-if="item.children && item.children.length > 0"><template #title><el-icon v-if="item.meta.icon"><component :is="item.meta.icon"></component></el-icon><span>{{ item.name }}</span></template><template v-for="(child, ci) in item.children" :key="ci"><el-menu-item :index="child.path"><el-icon><component :is="child.meta.icon"></component></el-icon>{{ child.name }}</el-menu-item></template></el-sub-menu></template></el-menu></div>
</template>
<script setup>
import { computed,ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
const router = useRouter();
const route = useRoute();const treeData = router.getRoutes().filter((v) => v.meta && v.meta.requiresAuth);const defaultActive = computed(() => route.path || treeData.value[0].path)
const isCollapse = ref(false)
</script>