【解决】Vue3中使用element-plus菜单点击两次才高亮显示问题

【解决】Vue3中使用element-plus菜单点击两次才高亮显示问题

原因 :我这里造成高亮点击两次才生效的原因是重复渲染造成default-active的值重置了。
状况 :点击菜单后,地址栏改变、页面也跳转,但要点击第二次后才高亮显示。或者点击第一次时会高亮在主页。调试发现,第一次点击在执行完handleSelect 函数后会执行一次const activeIndex = ref('/')。这是造成的该问题的关键。
解决办法 :最有效快速的解决办法就是设置 activeIndex 为当前路由

...

关键代码:

typescript 复制代码
import { onMounted  } from 'vue';
onMounted(() => {
  // 设置 activeIndex 为当前路由,避免重新渲染造成活动状态重置
  activeIndex.value = router.currentRoute.value.path;
});

完整代码

typescript 复制代码
<template>
  <div class="nav-container">
    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" background-color="#2A3796"
       text-color="#fff" active-text-color="#ffd04b" @select="handleSelect">
       <el-menu-item index="/" :exact="true">主页</el-menu-item>
       <el-menu-item index="/one" :exact="true">菜单一</el-menu-item>
       <el-menu-item index="/two" :exact="true">菜单二</el-menu-item>
       <el-menu-item index="/three" :exact="true">菜单三</el-menu-item>
     </el-menu>
  </div>
</template>

<script lang="ts" setup>
import { ref,onMounted  } from 'vue';
import { useRouter } from 'vue-router';

const activeIndex = ref('/')
const router = useRouter();

onMounted(() => {
  // 设置 activeIndex 为当前路由,避免重新渲染造成活动状态重置
  activeIndex.value = router.currentRoute.value.path;
});

const handleSelect = (index: string) => {
  activeIndex.value = index;
  router.push(index);
};

</script>
相关推荐
ai小鬼头19 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
wen's26 分钟前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim1 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim1 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
aha-凯心1 小时前
vben 之 axios 封装
前端·javascript·学习
漫谈网络1 小时前
WebSocket 在前后端的完整使用流程
javascript·python·websocket
遗憾随她而去.2 小时前
uniapp 中使用路由导航守卫,进行登录鉴权
前端·uni-app
xjt_09012 小时前
浅析Web存储系统
前端
foxhuli2292 小时前
禁止ifrmare标签上的文件,实现自动下载功能,并且隐藏工具栏
前端