:router="true"
一、參考文章
vue3:十一、主頁面布局(實現基本左側菜單+右側內容效果)-CSDN博客
參考上述文章可知,頁面跳轉是通過在js中定義的菜單中攜帶的path,然后通過菜單的點擊事件完成的跳轉,現在可以進行優化,直接將路徑寫入視圖層的菜單標題即可完成跳轉
二、具體實現
1、移除click事件
2、在菜單容器中寫入方法
開啟組件中頁面的路由功能
這里的路由跳轉是根據index的值進行的跳轉?,現在索引寫的都是1,2,3...;1-1,1-2,1-3...,所以需要替換成具體路徑
例如:
修改前,點擊一個菜單進行跳轉
?對應的路徑就顯示的是當前index的信息
所以需要將這個index修改為指定的路徑
3、修改index
index其實應該是一個唯一的值,只要各個標題之間不重復就行
將index的值修改為對應的path,這里只是具體要跳轉的標題才是使用跳轉功能,像可展開項的容器就無需跳轉,直接采用之前的索引即可
三、完整代碼
src/layout/index.vue
<template><el-container class="layout-container-demo" style="height: 100vh"><el-aside width="200px"><el-scrollbar><!-- default-openeds:默認展開菜單 --><el-menu :default-openeds="['1', '2']" :router="true"><!-- 遍歷一級菜單 --><template v-for="(item, index) in menu" :key="index"><!-- 如果一級菜單有子菜單,渲染 el-sub-menu --><el-sub-menu v-if="item.children && item.children.length > 0" :index="`${index + 1}`"><template #title><el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>{{ item.name }}</template><!-- 遍歷二級菜單 --><el-menu-item v-for="(secondmenu, secondindex) in item.children" :key="secondindex":index="secondmenu.path">{{ secondmenu.name }}</el-menu-item></el-sub-menu><!-- 如果一級菜單沒有子菜單,渲染 el-menu-item --><el-menu-item v-else :index="item.path"><el-icon v-if="item.icon"><component :is="item.icon" /></el-icon>{{ item.name }}</el-menu-item></template></el-menu></el-scrollbar></el-aside><el-container><el-header style="text-align: right; font-size: 12px"><div class="toolbar"><el-dropdown><el-icon style="margin-right: 8px; margin-top: 1px"><setting /></el-icon><template #dropdown><el-dropdown-menu><el-dropdown-item>View</el-dropdown-item><el-dropdown-item>Add</el-dropdown-item><el-dropdown-item>Delete</el-dropdown-item></el-dropdown-menu></template></el-dropdown><span>Tom</span></div></el-header><!-- 右側內容 --><el-main><el-scrollbar><RouterView /></el-scrollbar></el-main><!-- 底部信息 --><el-footer class="flex flex-center"><span>@2025-2030 wen</span></el-footer></el-container></el-container>
</template><script setup>
import { reactive } from 'vue'
// 菜單
const menu = reactive([{name: 'Navigator One',icon: "message",path: '/about',},{name: 'Navigator Two',icon: "message",children: [{name: 'Option 1',path: '/home',},{name: 'Option 2',},{name: 'Option 3',},{name: 'Option 4',},]},
]);
</script><style scoped>
.layout-container-demo .el-header {position: relative;background-color: var(--el-color-primary-light-7);color: var(--el-text-color-primary);
}.layout-container-demo .el-aside {color: var(--el-text-color-primary);background: var(--el-color-primary-light-8);
}.layout-container-demo .el-menu {border-right: none;
}.layout-container-demo .el-main {padding: 0;
}.layout-container-demo .toolbar {display: inline-flex;align-items: center;justify-content: center;height: 100%;right: 20px;
}
</style>