vue-element-admin面包屑導航分析


面包屑導航

1.el-breadcrumb-item

  • el-breadcrumb:面包屑導航容器,separator 控制面包屑導航文本中分割線
  • el-breadcrumb-item:面包屑子項目,可以使用 to 屬性切換路由,slot 中可以包含 a 標簽來跳轉到外鏈
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首頁</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">活動管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>活動列表</el-breadcrumb-item>
      <el-breadcrumb-item>活動詳情</el-breadcrumb-item>
    </el-breadcrumb>

    使用 to 屬性和 a 標簽切換路由區別是:to 屬性切換路由是動態替換 App.vue 中的路由內容,而 a 標簽切換路由會刷新頁面

2.路由與面包屑導航映射

面包屑導航最大的難度在於如何將路由與面包屑導航進行映射,下面我們一起看看 vue-element-admin 如何實現:

 

2.1.生成面包屑導航

getBreadcrumb() {
  let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
  const first = matched[0]

  if (!this.isDashboard(first)) {
    matched = [{ path: '/dashboard', meta: { title: 'Dashboard' }}].concat(matched)
  }

  this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
}
  • 獲取 this.$route.matched,並過濾其中不包含 item.meta.title 的項,生成新的面包屑導航數組 matched
  • 判斷 matched 第一項是否為 dashboard,如果不是,則添加 dashboard 為面包屑導航第一項
  • 再次過濾 matched 中 item.meta.title 為空的項和 item.meta.breadcrumb 為 false 的項
這里的關鍵是 this.$route.matched 屬性,它是一個數組,記錄了路由的匹配過程,這就是面包屑導航實現的基礎

 

isDashboard 實現如下:

isDashboard(route) {
  const name = route && route.name
  if (!name) {
    return false
  }
  return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
}

2.2.渲染面包屑導航

面包屑導航模板源碼:

<el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect'||index==levelList.length-1" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
</el-breadcrumb>

el-breadcrumb-item 內做了一個判斷,如果是最后一個元素或者路由的 redirect 屬性指定為 noRedirect 則不會生成鏈接,否則將使用 a 標簽生成鏈接,但是這里使用了 @click.prevent 阻止了默認 a 標簽事件觸發,而使用自定義的 handleLink 方法處理路由跳轉,handleLink 方法源碼如下:

handleLink(item) {
  const { redirect, path } = item
  if (redirect) {
    this.$router.push(redirect)
    return
  }
  this.$router.push(this.pathCompile(path))
}

這里的 pathCompile 用於解決動態路由的匹配問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM