你需要在 Vue Router 中设置 'router-link-active' 类来高亮当前选中的菜单项。你可以使用 'exact-active-class' 属性来设置精确匹配时的激活类。对于 'el-menu' 组件,你还需要设置 'default-active' 属性来指定默认激活的菜单项。

下面是一个示例代码:

<template>
  <el-menu :default-active="$route.path" class="el-menu-demo" mode="horizontal">
    <el-menu-item index="/">首页</el-menu-item>
    <el-submenu index="/products">
      <template slot="title">产品</template>
      <el-menu-item index="/products/list">产品列表</el-menu-item>
      <el-menu-item index="/products/new">添加产品</el-menu-item>
    </el-submenu>
    <el-menu-item index="/about">关于我们</el-menu-item>
  </el-menu>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '/'
    }
  },
  watch: {
    $route(to) {
      this.activeIndex = to.path
    }
  }
}
</script>

<style>
.el-menu-demo {
  margin-bottom: 20px;
}
</style>

在上面的代码中,我们使用 '$route.path' 作为 'default-active' 属性的值,这样就可以根据当前路由路径来设置默认选中的菜单项。我们还使用 '$route' 对象的 'watch' 属性来监听路由变化,并根据新的路由路径来更新当前选中的菜单项。

如果你想要精确匹配路由路径,可以添加 'exact-active-class' 属性来设置精确匹配时的激活类。例如:

<el-menu-item index="/" exact-active-class="is-active">首页</el-menu-item>

这样就会在当前路由路径为 '/' 时添加 'is-active' 类。

希望对你有帮助!

Vue Router el-menu 子菜单高亮:如何实现父级菜单选中状态

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

免费AI点我,无需注册和登录