【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()
})
相关推荐
崔庆才丨静觅3 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60614 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了4 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅4 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅4 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅5 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment5 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅5 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊5 小时前
jwt介绍
前端
爱敲代码的小鱼5 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax