我在做一个后台管理系统,关于menu选中,我碰到了一些问题:首选
1登录进去后,需要默认选中一个菜单项,比如首页。在menu标签中使用如下代码实现:
:default-active="main",其中main是我首页menu-items对应的index。
但是上面的代码引起了两个问题:
手动点击选中某个menu-item后,比如order,再刷新,页面路由还是https://xxx/order,但是菜单上选中的却是首面。
另外还有一个问题,如果我在一个页面上跳到另一个页面,路由发生了变化,但是菜单选中态还是没有跟着改变。
针对这两个问题,研究了一番,最后终于解决了。现在把解决方案写下来。
/****************menu选中态,很重要,开始 */
import { useRoute } from 'vue-router';
const route = useRoute();
console.info("当前route:"+ route.path);
const activeMenu = ref(route.path); //path带有斜线 '/main' ,menu-items里的index也要带斜线,与index对应上才会显示选中态
watch(() => route.path, (newPath) => {
// 监听路由变化,更新菜单选中状态
activeMenu.value = newPath;
console.info("新route:"+newPath)
});
/***************menu选中态,很重要,结束 */
<el-container class="layout-container">
<el-aside width="200px">
<img src="../assets/main_logo.png" style="width: 90%; margin: 20px auto;">
<!-- element-plus的菜单标签 -->
<el-menu :default-active="activeMenu" background-color="#0044FF" text- color="#fff" router>
<el-menu-item class="custom-menu-item" index="/main">
<el-icon><HomeFilled /></el-icon>
<span>首页</span>
</el-menu-item>
<el-menu-item class="custom-menu-item" index="/promote">
<el-icon>
<Management />
</el-icon>
<span>推广</span>
</el-menu-item>
<el-menu-item class="custom-menu-item" index="/order">
<el-icon><Iphone /></el-icon>
<span>订单</span>
</el-menu-item>
</el-menu>
</el-aside>
</el-container>
:default-active 指定的就是el-menu-item里的index,制定哪个index,哪个menu就是选中态 。 使用动态的ref设置 activeMenu就能动态设置选中菜单。但要注意的一点是,route.path取到的值是带有斜线的,例如/main,所以el-menu-item设置的index也要带上斜线,否则就不会出现选中态。