vue3 + ts + element-plus 菜单高亮激活跳转,刷新后继续高亮刷新前的菜单选项。

该代码示例展示了如何在Vue.js应用中使用el-menu组件创建横向菜单,并结合vue-router实现点击菜单选项后的页面跳转和高亮选中效果。同时,它利用sessionStorage保存当前选中菜单,以实现页面刷新后仍能保持之前的选择。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图:
在这里插入图片描述

<template>
  <el-menu
    :default-active="activeIndex" //激活的菜单选项
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"  //点击菜单选项后的事件
  >
    <el-menu-item index="mainPage">首页</el-menu-item>
    <el-menu-item index="batteryClusterInformation">电池簇信息</el-menu-item>
    <el-menu-item index="realTimeAlarm">实时告警</el-menu-item>
    <el-menu-item index="parameterConfiguration">参数配置</el-menu-item>
    <el-menu-item index="historicalData">历史数据</el-menu-item>
    <el-menu-item index="debuggingManagement">调试管理</el-menu-item>
    <el-menu-item index="systemSetting">系统管理</el-menu-item>
  </el-menu>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

let activeIndex = ref<string>("");
const handleSelect = (key: string, keyPath: string[]): void => {
  sessionStorage.setItem("currIdx", key);  //保存点击后的菜单选项
  if (keyPath !== null || keyPath !== undefined) {//不为空则高亮对应key的菜单选项(key=index)
    if (keyPath) {
      activeIndex.value = key;//将activeIndex设为key,则高亮key对应的菜单
    }
  }
  router.push(`/main/${key}`);  //跳转到对应菜单选项的页面
};
// 获取刷新之前的path,如果没有,指定一个默认的
const currIdx = sessionStorage.getItem("currIdx");  //获取刷新前保存的菜单选项
activeIndex.value = currIdx ? currIdx : "mainPage"; //如果currIdx 不存在,则给一个默认激活的菜单

</script>
<style scoped>
.el-menu--horizontal {
  border: none;
}
.el-menu-demo {
  height: 74px;
}
</style>

补充知识:

以 / 开头的嵌套路径会被当做根路径。

// 在main下的页面进行跳转时,只写子路由的路径,路由会自动加上父路由
router.push('mainPage');
// 写完整路径
router.push('/main/mainPage');

PS:没有实现点击页面中的按钮跳转页面还能激活菜单选项(QAQ),有没有大佬赐教。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值