时间:2020-11-23 11:54:33 | 栏目:vue | 点击:次
前言
最近在工作中遇到了一个问题,是关于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}, ] }
总结