vue动态面包屑兼容全路径回退(含上级路径参数)

本文介绍了一种在Vue应用中优化面包屑导航的方法,解决了带有参数的路由在生成面包屑时无法正确显示的问题。通过将全路径参数(fullPath)加入到路由匹配对象(matched)中,实现了动态面包屑的准确跳转。

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

需求

如嵌套路由, 一级是/home, 二级是/home/user, 这种做成动态面包屑点击面包屑内容从二级/user跳转回一级/home是完全没有问题的.

但是如果home带有参数如/home?id=1, 那么vue的$route的matched是拿不到?id=1的, 只有全路径fullPath参数才能拿到.

如图面包屑需要的是fullPath,但是面包屑是根据matched生成的, 而matched里面没有fullPath

解决思路: 把fullPath放入matched中

解决代码如下

// js
data() {
    return {
      newRoute: {},
    }
},
watch: {
    $route: function(to) {
      const { fullPath, matched } = to
      // 全路径存储
      matched[matched.length - 1].fullPath = fullPath
      // 保留上一次父级全路径
      const fromMatched = this.newRoute.matched
      if (fromMatched && fromMatched.length < matched.length) {
        fromMatched.push(matched[matched.length - 1])
        this.newRoute = { ...to, matched: fromMatched }
      } else {
        this.newRoute = { ...to, matched: matched }
      }
    },
},
// html
<t-breadcrumb
      v-if="newRoute.matched && newRoute.matched.length > 0"
    >
      <template v-slot:default>
        <template v-for="(item, index) in newRoute.matched">
          <t-breadcrumbItem
            v-if="item.name"
            :to="item.fullPath ? item.fullPath : item.path"
            :key="index"
            >{{ item.name }}</t-breadcrumbItem
          >
        </template>
      </template>
      <template v-slot:separator>/</template>
</t-breadcrumb>

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

喜樂的CC

年龄大身体差但记得你的打赏~

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

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

打赏作者

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

抵扣说明:

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

余额充值