Vue el-menu 进入详情页父级菜单高亮实现方法
要使 Vue el-menu 进入详情页后父级菜单高亮,您需要使用以下方法:
- 在路由中定义每个页面的路径和菜单的名称和路径。
- 在 el-menu 组件上使用 :default-active 属性,该属性将当前激活的菜单项设置为指定的菜单项。
- 在路由的 beforeEach 钩子函数中,获取当前路由的路径,然后设置高亮的菜单项。
以下是示例代码:
// 路由配置
const routes = [
{
path: '/',
redirect: '/home',
meta: { title: '首页', icon: 'el-icon-s-home' }
},
{
path: '/home',
component: Home,
meta: { title: '首页', icon: 'el-icon-s-home' }
},
{
path: '/about',
component: About,
meta: { title: '关于我们', icon: 'el-icon-info' }
},
{
path: '/detail',
component: Detail,
meta: { title: '详情页', icon: 'el-icon-s-platform' }
}
];
// el-menu 组件
<el-menu :default-active="$route.path" class="el-menu-vertical-demo" @select="handleSelect">
<el-menu-item index="/home" :route="{path:'/home'}">
<i class="el-icon-s-home"></i>
<span slot="title">首页</span>
</el-menu-item>
<el-menu-item index="/about" :route="{path:'/about'}">
<i class="el-icon-info"></i>
<span slot="title">关于我们</span>
</el-menu-item>
<el-submenu index="detail">
<template slot="title">
<i class="el-icon-s-platform"></i>
<span>详情页</span>
</template>
<el-menu-item index="/detail" :route="{path:'/detail'}">
<span slot="title">详情</span>
</el-menu-item>
</el-submenu>
</el-menu>
// 路由 beforeEach 钩子函数
router.beforeEach((to, from, next) => {
const activePath = to.path;
const item = this.$refs.menu.$children.find(item => item.$el.classList.contains('is-active'));
if (item) {
item.$el.classList.remove('is-active');
}
const selectedItem = this.$refs.menu.$children.find(item => item.index === activePath);
if (selectedItem) {
selectedItem.$el.classList.add('is-active');
}
next();
});
在上面的示例中,路由配置中定义了每个页面的路径和菜单的名称和路径。el-menu 组件上使用 :default-active 属性,该属性将当前激活的菜单项设置为指定的菜单项。在路由的 beforeEach 钩子函数中,获取当前路由的路径,然后设置高亮的菜单项。最后,使用 classList.add() 和 classList.remove() 方法添加和删除 is-active 类,以便高亮选定的菜单项。
原文地址: https://www.cveoy.top/t/topic/mITC 著作权归作者所有。请勿转载和采集!