需求

如嵌套路由, 一级是/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>

Logo

前往低代码交流专区

更多推荐