vue3:十一、主页面布局(优化页面跳转方式)
: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>