【Element Plus】Menu组件:url访问页面时高亮对应菜单栏

文章目录

场景

使用Element Plus的Menu 菜单 | Element Plus时,点击对应菜单会显示对应路由,此时会高亮选中菜单栏。但输入url访问对应路径,菜单栏不会默认高亮。

需求:url访问页面时高亮对应菜单栏。

代码

router:

javascript 复制代码
import { createRouter, createWebHistory } from 'vue-router'

export const routes = [
  {
    path: '',
    title: '功能Demo',
    // 父组件的component中要有<router-view></router-view>才会渲染子组件。实际上我们并不需要这个父组件
    children: [
      {
        path: '/shopping-link',
        name: 'shoppingLink',
        title: '复制链接弹出信息',
        component: () => import('@/views/shoppingLink.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes: routes,
})

export default router

Menu:

javascript 复制代码
<template>
  <div class="menu">
    <el-menu
      active-text-color="#ffd04b"
      background-color="#545c64"
      class="el-menu-vertical-demo"
      text-color="#fff"
      :router="true"
    >
      <el-sub-menu v-for="item in routes" :index="item.path">
        <template #title>{{ item.title }}</template>
        <el-menu-item v-for="i in item.children" :index="i.path" :route="i.path" :key="i.path">
          {{ i.title }}
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>
<script lang="ts" setup>
import { routes } from '@/router/index'

</script>

<style lang="less" scoped>
.menu {
  width: 200px;
  height: 100%;
  background-color: #545c64;
  .el-menu {
    border: none;
  }
}
</style>

解决

Menu API:default-active
default-active可以设置默认高亮的菜单。当default-active的值匹配上el-menu-itemindex时,对应el-menu-item会高亮。

我们这里菜单el-menu-itemindex是路径,因此:进入页面时,获取路径,赋值给default-active即可。

html 复制代码
    <el-menu
      active-text-color="#ffd04b"
      background-color="#545c64"
      class="el-menu-vertical-demo"
      text-color="#fff"
      :default-active="activePath" 
      :router="true"
    >
javascript 复制代码
import { ref, onMounted } from 'vue'
const activePath = ref('')

// 默认高亮
const getPath = () => {
  const path = location.pathname
  activePath.value = path
}

onMounted(() => {
  getPath()
})
相关推荐
前端H8 小时前
生成式 UI 实战:AI 如何重塑前端界面
前端·人工智能·ui
触底反弹8 小时前
🚀 Node.js path 和 fs 模块,从回调地狱到 async/await 的进化之路!
javascript·后端·node.js
懂懂tty8 小时前
Web前端性能指标
前端
绝世唐门三哥8 小时前
vue3中页面返回时刷新首页的处理方案
开发语言·前端·javascript
sugar__salt9 小时前
Node.js path 与 fs 核心模块完全指南 —— 从路径处理到异步流程控制
javascript·node.js
东方小月9 小时前
agent-skills:把资深工程师的‘工作流’,装进你的AI编程里
前端·架构·代码规范
Maynor9969 小时前
AI Coding 零基础实战教程|第五部分:完整项目案例实操
java·前端·人工智能·claude code·ai coding
binbin_529 小时前
React 井字棋教程:用一个小游戏理解组件和状态
前端·react.js·前端框架
梦曦i9 小时前
uni-router新推useUniEventChannel,彻底解决页面通信难题
前端·uni-app
柯克七七10 小时前
给老项目加了 TypeScript,本来只想自己爽,结果全公司代码审查标准被我抬高了
前端·vue.js·typescript