解决vue3 el-menu 刷新页面菜单选中项和路由不匹配

网上找到的方法有2种:

1、给el-menu组件增加属性

:default-active="this.$route.path"

但是博主试了下,打印出来的路由this.$route.path一直是/,放弃

2、通过this.$router.currentRoute

console.log('当前路由', this.$router.currentRoute);

在这里插入图片描述

 所以我们可以通过this.$router.currentRoute._value.fullPath访问到当前激活的url,然后将default设置为这个值,我们的这个问题就解决了

具体代码: 

//el-menu里进行数据绑定
<el-menu
      background-color="#333744"
      text-color="#fff"
      active-text-color="#ffd04b"
      :unique-opened="true"
      :default-active="paths"
       router >
//在script中数据赋值
data() {
    return {
      paths: this.$router.currentRoute._value.fullPath.split("/")[1],
     }
}

然鹅,我打印this.$router.currentRoute 可以看到路由._value.fullPath的值,但是直接打印 this.$router.currentRoute._value.fullPath 就一直是/,无奈,继续放弃

3、使用window.location.hash.replace('#', '')

获得hashPath后,设定:

:default-active="currentPathIndex"

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vueel-menu组件可以通过设置`default-active`属性来实现高亮当前选中菜单项,而实现点击菜单项跳转由可以通过设置`router`属性和使用`router-link`组件来实现。 首先,设置el-menu组件的`default-active`属性,将其绑定到Vue实例中的一个data属性,例如`activeMenu`: ```html <template> <div> <el-menu :default-active="activeMenu"> <el-menu-item index="/home">首页</el-menu-item> <el-menu-item index="/about">关于</el-menu-item> <el-menu-item index="/contact">联系我们</el-menu-item> </el-menu> <router-view></router-view> </div> </template> <script> export default { data() { return { activeMenu: '/home' // 默认选中首页菜单项 } } } </script> ``` 然后,在由配置中,使用Vue Router的`router-link`组件来实现点击菜单项跳转由。在每个菜单项上使用`router-link`组件,将其绑定到相应的径: ```html <template> <div> <el-menu :default-active="activeMenu"> <el-menu-item index="/home"> <router-link to="/home">首页</router-link> </el-menu-item> <el-menu-item index="/about"> <router-link to="/about">关于</router-link> </el-menu-item> <el-menu-item index="/contact"> <router-link to="/contact">联系我们</router-link> </el-menu-item> </el-menu> <router-view></router-view> </div> </template> ``` 这样,点击菜单项时会根据`router-link`中的`to`属性自动跳转到对应的由,并且el-menu组件会根据当前由的径自动高亮对应的菜单项。 请注意,以上代码中的el-menu和router-view是使用了Element UI库和Vue Router插件,你需要在项目中引入并正确配置它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hzxOnlineOk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值