前言
最近在工作中遇到了一個問題,是關于vue動態路由多級嵌套面包屑怎么弄(不是動態路由嵌套可以嘗試用 this.$route.matched方法獲取到path和name集合,動態的嵌套獲取不到全部具體的id)
功能比如:A列表頁面路由如/a,點擊任意一列進入任意一個A的詳情頁面名字為B,/b/03(這個是動態路由弄是吧,03就是id嘛),點擊B頁面任意一列,再進入B的詳情頁名字為C,路由如/bdetail/01;現在弄面包屑要獲取到的路由是剛剛打開的,如(/a;/b/03;/bdetail/01)
思路:獲取所有進入的層級的路由和名稱如breadlist=[{path:'/a',name:'一級'},{path:'/b/03',name:'二級'},{path:'/bdetail/01',name:'三級'}] ,然后遍歷出來如: <span v-for="(item in breadlist)"><router-link :to="item.path">{{item.name}}</router-link></span>
做法
下面貼出相關代碼:
A列表頁面跳轉按鈕:(breadNum記錄面包屑層級)
<router-link :to="{path:'/b/'+id,query:{breadNum:2}}"></router-link>B列表頁面跳轉按鈕:
<router-link :to="{path:'/bbdetail/'+id,query:{breadNum:3}}"></router-link>breadcrumb.vue頁面:
<template>  <div class="breadbox">   <span v-for="(item,index) in breadlist" >    <router-link :to="item.path">{{item.name}}</router-link>   </span>  </div></template><script> export default{  created() {   this.getBreadcrumb();  },  data() {   return {    breadlist: '' // 路由集合   }  },  methods: {   getBreadcrumb() {    var breadNumber= this.$route.query.breadNum || 1;//url變量breadNum記錄層級,默認為1,如果大于1,要添加上變量;    var breadLength=this.$store.state.breadListState.length;//目前breadlist集合數組個數    var curName=this.$route.name;    var curPath=this.$route.fullPath;    var newBread={name:curName,path:curPath};    var ishome=curName=='首頁';    console.log(ishome);    if(breadNumber===1){//點擊一級菜單     this.$store.commit('breadListStateRemove',1);//初始化,只有首頁面包屑按鈕     if(!ishome)//如果不是首頁      this.$store.commit('breadListStateAdd',newBread);//當前頁面添加到breadlist集合    }    else if(breadLength<=breadNumber){//如果不是一級導航,并且breadlist集合個數等于或者小于目前層級     this.$store.commit('breadListStateAdd',newBread);//要把當前路由添加到breadlist集合    }else{     this.$store.commit('breadListStateRemove',parseInt(breadNumber)+1);//如果往回點面包屑導航,截取;    }    this.breadlist=this.$store.state.breadListState;    console.log(this.breadlist);   }  },  watch: {   $route () {    this.getBreadcrumb();   }  }, }</script>狀態管理store.js代碼:
export default store = new Vuex.Store({ state: { breadListState:[  {name:'首頁',path:'/'} ] }, mutations: { breadListStateAdd(state,obj){  state.breadListState.push(obj); }, breadListStateRemove(state,num){  state.breadListState=state.breadListState.slice(0,num); } }})路由route.js代碼:
{ path: '/', name: '首頁', component: Main, redirect:'/home', children:[  {path: '/a',name: 'A頁面',component: APage},  {path: '/b/:id',name: 'B頁面',component: BPage},  {path: '/bdetail/:id',name: 'C頁面',component: CPage}, ]} 總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答