Vue后台面包屑导航实现

1.基础知识

$route.matched  类型: Array<RouteRecord>
一个数组,包含当前路由的所有嵌套路径片段的路由记录 。路由记录就是 routes 配置数组中的对象副本 (还有在 children 数组)。
const router = new VueRouter({
  routes: [
    // 下面的对象就是路由记录
    {
      path: '/foo',
      component: Foo,
      children: [
        // 这也是个路由记录
        { path: 'bar', component: Bar }
      ]
    }
  ]
})
当 URL 为 /foo/bar,$route.matched 将会是一个包含从上到下的所有对象 (副本)。

2.代码 (项目使用的时element-ui的el-breadcrumb组件)

<template>
  <el-breadcrumb separator="/">
    <!-- 添加动画 -->
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) of list" :key="item.path">
        <span v-if="index == list.length - 1">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import pathToRegexp from 'path-to-regexp'
export default {
  data() {
    return {
      list: []
    }
  },
  watch: {
    // 当路由发生改变时执行
    $router() {
      this.getBreadcrumb()
    }
  },
  // 首次执行
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      // matched 包含当前路由的所有嵌套路径片段的路由记录<Array>
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]
      // 默认显示Home,可根据项目自行调整
      if (!this.isHome(first)) {
        matched = [{ path: '/home', meta: { title: '首页' }}].concat(matched)
      }
      this.list = matched
    },
    isHome(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Home'
    },
    handleLink(item) {
      const { redirect, path } = item
      // 优先执行redirect指定路径
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    },
    pathCompile(path) {
      // 解决面包屑不支持:id的方式 https://github.com/PanJiaChen/vue-element-admin/issues/561
      const { params } = this.$route
      const toPach = pathToRegexp.compile(path)
      return toPach(params)
    }
  }
}
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值