最近在写vue3+ElementPlus的一个后台项目,项目中只显示左侧边栏三个菜单,但其实每个菜单下都有一些子页面。想实现的效果是进入子菜单页面,其对应的父菜单仍然显示选中效果。
思路
在需要实现这种效果的子菜单路由上添加父菜单path,相当于加个识别标志。再在组件那里统一控制即可。
实现
// 子菜单路由添加父菜单path
{
path:"fatherPage",
name:"fatherPage",
component: FatherPage,
meta:{
title:"父菜单"
}
},
{
path:"sonPage",
name:"sonPage",
component: SonPage,
meta:{
title:"子菜单",
activePath:"fatherPage"
}
}
// 菜单组件
const onRoutes = computed(()=>{
if(route.meta.activePath){
return route.meta.activePath
}
return route.path
})
// 注意el-menu中需要先设置:default-active="onRoutes"
注意:有的时候activePath直接写父组件的path效果不生效,这时候可以打印一下route数据,具体看下里面的path,有的会加前缀,自己改下activePath即可。