解决方法:在 <el-menu>
的 @select
事件中调用了 handleMenuSelect
方法来处理菜单项的选择。你可以在 handleMenuSelect
方法中根据菜单项的 index
来执行相应的操作,例如更新组件内的数据或者切换组件。由于整个页面的路由路径并没有改变,因此不会触发整个页面的路由跳转,只会更新 <router-view>
中的内容。这样就实现了只更新 <router-view>
中内容的效果。
home组件
<template>
<div class="container">
<el-container>
<!-- 头部 -->
<el-header>Header</el-header>
<el-container>
<!-- 侧边栏 -->
<el-col :span="12" :style="{ 'width': '200px' }">
<el-menu default-active="first" class="el-menu-vertical-demo" @select="handleMenuSelect">
<el-menu-item index="first">
<i class="el-icon-menu"></i>
<span slot="title">首页</span>
</el-menu-item>
<el-menu-item index="person">
<i class="el-icon-menu"></i>
<span slot="title">个人中心</span>
</el-menu-item>
<el-menu-item index="personal">
<i class="el-icon-document"></i>
<span slot="title">成绩管理</span>
</el-menu-item>
<el-menu-item index="score">
<i class="el-icon-setting"></i>
<span slot="title">人员管理</span>
</el-menu-item>
</el-menu>
</el-col>
<!-- 主要内容 -->
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
export default {
methods: {
handleMenuSelect(index) {
const targetPath = '/' + index;
// 判断目标路径是否与当前路径相同
// 通过 this.$route.path 获取到当前路由的路径
if (this.$route.path === targetPath) {
// 如果相同则不进行导航
return;
}
// 否则进行导航
this.$router.push({ path: targetPath });
}
}
};
</script>
<style scoped>
.container {
width: 1200px;
margin: 0 auto;
}
.el-header {
background-color: #B3C0D1;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
text-align: center;
}
.el-main {
height: 600px;
background-color: #E9EEF3;
}
body>.el-container {
margin-bottom: 40px;
}
</style>
路由:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import home from '@/view/home' //引入需要用的组件
import login from '@/view/login' //引入需要用的组件
import first from '@/view/aside/first'
import person from '@/view/aside/person'
import personal from '@/view/aside/personal'
import score from '@/view/aside/score'
const routes = [
{
path: '/',
redirect: '/home' // 将根路径重定向到 home 路由
},
{
path: '/home',//路由地址
name: 'home',
component: home,//相对应的组件
redirect:{name:"first"},
children:[
{
path: '/first',
name: 'first',
component: first
},
{
path: '/person',
name: 'person',
component: person
},
{
path: '/personal',
name: 'personal',
component: personal
},
{
path: '/score',
name: 'score',
component: score
}
]
},
{
path: '/login',
name: 'login',
component: login
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
});
export default router
目录