需要实现的效果:
一级 / 二级 /三级
不是很清楚别人怎么写的,就是自己用搜索写了个,好处是每个页面都会重新计算,不依赖于上一个页面路径
Header.vue里面的methods相关代码:
getBreadList(){
let currentPath=this.$route.path;
let routes=this.$router.options.routes;
return this.breadListSearch(routes,currentPath);
},
breadListSearch(routes,currentPath,breadList){
breadList=breadList||[];
breadList=[...breadList];
for (let i = routes.length-1; i >=0 ; i--) {
if(routes[i].path===currentPath){
if(routes[i].meta&&routes[i].meta.info)
breadList.push({'path':routes[i].path,'info':routes[i].meta.info});
return breadList;
}else{
if(routes[i].children&¤tPath.indexOf(routes[i].path)===0){
breadList.push({'path':routes[i].path,'info':routes[i].meta.info});
return this.breadListSearch(routes[i].children,currentPath,breadList,);
}
}
}
}
路由配置相关代码:
const routes = [
{
path: "/",
name:'Manage',
component:()=>import('../views/Manage'),
redirect: '/home',
meta:{
info:'首页'
},
children:[
{
path:"/user",
name:'User',
meta:{
info:'用户管理'
},
component:()=>import('../views/User')
},
{
path:"/home",
name:'Home',
component:()=>import('../views/Home')
}
]
}
]
注意:重定向去往的路由组件里面不要写meta对象,哪里写的重定向,写在那里,因为这个算法是从树根从上到下搜索的
面包屑代码:
<el-breadcrumb separator="/" style="display: inline-block;margin-left: 10px">
<el-breadcrumb-item v-for="item in this.getBreadList()" :to="item.path" :key="item.path" >
{{item.info}}
</el-breadcrumb-item>
</el-breadcrumb>
实现思路:
获取当前要渲染的路由组件的path路径,获取路由的树形层级组件信息,从上到下进行path字符串前缀匹配
举例:当前path:/user/info/edit,从根路由搜索path为/user的节点,从该节点继续搜索children的path等于/user/info的子节点,搜到后从这个节点继续搜children的path等于/user/info/edit的子节点,搜到后,终止搜索,这一条路径就是这个面包屑的层级.