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

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

<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),有没有大佬赐教。

猜你喜欢

转载自blog.csdn.net/weixin_45288172/article/details/130367610