Vue Router el-menu 子菜单高亮:如何让父级菜单也高亮
在 Vue Router 中,可以通过 'router-link-active' 类来为当前激活的路由添加样式。而对于 el-menu 组件的子菜单,同样可以使用 'router-link-active' 来设置高亮样式。
但是,在 el-menu 组件中,父级菜单不会自动高亮。这是因为 el-menu 组件默认只会为当前路由所匹配的最深层子菜单添加 'router-link-active' 类,而不会为父级菜单添加该类。
要解决这个问题,可以使用 Vue Router 提供的 'router.match' 方法来获取当前路由匹配的所有路由记录,然后通过遍历这些记录来找到父级菜单并为其添加 'router-link-active' 类。
具体实现方式如下:
- 在 el-menu 组件的 'active-name' 属性中,使用动态绑定语法 ':active-name="getActiveName"',并在 methods 中添加 'getActiveName' 方法,该方法返回当前路由的名称。
<el-menu :default-active="$route.path" :active-name="getActiveName">
<el-submenu index="sub1">
<template slot="title">菜单1</template>
<el-menu-item index="/menu1-1">菜单1-1</el-menu-item>
<el-menu-item index="/menu1-2">菜单1-2</el-menu-item>
</el-submenu>
<el-submenu index="sub2">
<template slot="title">菜单2</template>
<el-menu-item index="/menu2-1">菜单2-1</el-menu-item>
<el-menu-item index="/menu2-2">菜单2-2</el-menu-item>
</el-submenu>
</el-menu>
methods: {
getActiveName() {
const matched = this.$router.match(this.$route.path)
if (matched.length > 0) {
return matched[matched.length - 1].name
}
return ''
}
}
- 在 el-menu 组件的 'router' 属性中,使用 Vue Router 提供的 'afterEach' 钩子函数,在路由切换完成后调用一个方法来为父级菜单添加 'router-link-active' 类。该方法先获取当前路由匹配的所有路由记录,然后遍历这些记录,找到所有父级菜单并为其添加 'router-link-active' 类。
<el-menu :default-active="$route.path" :active-name="getActiveName" router>
<el-submenu index="sub1">
<template slot="title">菜单1</template>
<el-menu-item index="/menu1-1">菜单1-1</el-menu-item>
<el-menu-item index="/menu1-2">菜单1-2</el-menu-item>
</el-submenu>
<el-submenu index="sub2">
<template slot="title">菜单2</template>
<el-menu-item index="/menu2-1">菜单2-1</el-menu-item>
<el-menu-item index="/menu2-2">菜单2-2</el-menu-item>
</el-submenu>
</el-menu>
mounted() {
this.$router.afterEach(() => {
const matched = this.$router.currentRoute.matched
for (const record of matched) {
if (record.components.default.name === 'menu-item') {
record.instances.default.$el.classList.add('router-link-active')
}
}
})
}
需要注意的是,为了在菜单项被点击时自动收起子菜单,需要在 el-submenu 组件中添加 '@click="handleSubmenuClick"' 事件,并在 methods 中添加 'handleSubmenuClick' 方法,该方法通过调用 el-menu 组件的 'collapse' 方法来实现子菜单的收起。
<el-menu :default-active="$route.path" :active-name="getActiveName" router>
<el-submenu index="sub1" @click="handleSubmenuClick">
<template slot="title">菜单1</template>
<el-menu-item index="/menu1-1">菜单1-1</el-menu-item>
<el-menu-item index="/menu1-2">菜单1-2</el-menu-item>
</el-submenu>
<el-submenu index="sub2" @click="handleSubmenuClick">
<template slot="title">菜单2</template>
<el-menu-item index="/menu2-1">菜单2-1</el-menu-item>
<el-menu-item index="/menu2-2">菜单2-2</el-menu-item>
</el-submenu>
</el-menu>
methods: {
handleSubmenuClick() {
this.$nextTick(() => {
this.$refs.menu.collapse()
})
}
}
最终效果如下:

原文地址: https://www.cveoy.top/t/topic/mI1U 著作权归作者所有。请勿转载和采集!