根據路由記錄(利用matched)動態生成面包屑導航


動態面包屑效果:

  1、當路由為/home時,面包屑只展示一級

    

  2、當路由為/home/manage時,面包屑顯示一級和二級

    

  3、當路由為/home/manage/list或/home/manage/test時,面包屑顯示一級、二級、三級

    

    

 

實現:

  1、components/BreadCrumb.vue

<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item v-for="item in list" :key="item.path">
      <router-link :to="item.path">{{item.meta.title}}</router-link>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>
<script>
export default {
  computed: { list: (vm) => vm.$route.matched }
}
</script>

  components/Home.vue

<template>
  <div>
    <h1>首頁</h1>
    <router-view></router-view>
  </div>
</template>

  components/Manage.vue

<template>
  <div>
    <h1>活動管理</h1>
    <router-view></router-view>
  </div>
</template>

  components/List.vue

<template>
  <h1>活動列表</h1>
</template>

  components/Test.vue

<template>
  <h1>測試</h1>
</template>

 

  2、router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import Home from '@/components/Home'
import Manage from '@/components/Manage'
import List from '@/components/List'
import Test from '@/components/Test'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { title: '首頁' },
    children: [
      {
        path: 'manage',
        name: 'Manage',
        component: Manage,
        meta: { title: '活動管理' },
        children: [
          {
            path: 'list',
            name: 'List',
            component: List,
            meta: { title: '活動列表' }
          },
          {
            path: 'test',
            name: 'Test',
            component: Test,
            meta: { title: '測試' }
          }
        ]
      }
    ]
  }
]
const router = new VueRouter({
  mode: 'history',
  routes
})

export default router

 

  3、App.vue

<template>
  <div id="app">
    <BreadCrumb />
    <router-view></router-view>
  </div>
</template>
<script>
import BreadCrumb from '@components/BreadCrumb'
export default {
  components: { BreadCrumb }
}
</script>

 

解釋說明:

  1、home為一級路由,manage為二級路由,list和test為三級路由

  2、routes中對每個路由對象添加meta屬性,設置title

  3、BreadCrumb組件中通過vm.$route.matched獲取到路由信息list,遍歷該list生成動態面包屑

 


免責聲明!

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



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