【解决】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>
相关推荐
FRing0313 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng113 小时前
组件化服务端渲染模式SSR
前端
whitelbwwww14 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃14 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
Yannik14 小时前
在 Apple Silicon Mac 上用 Jenkins + Fastlane 搭建 iOS CI:从自动打包到 MR 检查流水线的完整实践
前端
Nayana14 小时前
《Web 到 HarmonyOS》-- 打包:Vite 产物 → HAP / HAR / HSP
前端
inksci15 小时前
用飞帆做了个小网页
前端·javascript·css·html
去伪存真15 小时前
被 pnpm 打包坑惨后,我彻底盘明白了硬链接与软链接
前端·electron
zhensherlock15 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
多加点辣也没关系18 小时前
JavaScript|第40章:JavaScript 工程化实践
开发语言·javascript·ecmascript