本篇文章小编给大家分享一下基于vue-router的matched实现面包屑功能代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
具体如下:
如上图所示,就是常见的面包屑效果,面包屑的内容一般来说,具有一定的层级关系,就以上图为例,首先是进入首页,然后点击左侧导航,进入活动管理下的活动列表页面,然后点击某一条数据,进入活动详情页面
这正好与vue-router的mached属性所获取的结果有着相似的原理,所以可以基于此来实现面包屑效果!
这里我使用了elementui的面包屑组件和导航菜单组件,先贴出最后的效果图:
路由配置
项目结构:
侧边导航栏是首页、电子数码、服装鞋帽页面都会显示的,所以我创建了一个layout组件,将这三个路由的component都指向该组件,并将导航栏和面包屑都写在layout组件中
因为该功能的实现依赖于路由的层级嵌套关系,所以要提前构思好路由的配置,我这里的路由配置如下:
const routes = [
//匹配空路由,重定向到根路由
{
path:'',
redirect: '/home',
meta:{
showInbreadcrumb:false
}
},
//根路由
{
path:'/home',
component: ()=>import('@/views/layout/index.vue'),
name:'home',
meta:{
title:"首页",
showInbreadcrumb:true
}
},
//电子数码
{
path:'/electronics',
name:'电子数码',
component: ()=>import('@/views/layout/index.vue'),
redirect: '/electronics/computer',
meta:{
title:"电子数码",
showInbreadcrumb:true
},
children:[
{
path:'computer',
name:'computer',
component()=>import('@/views/electronics/children/computer/index.vue'),
meta:{
title:"电脑",
showInbreadcrumb:true
}
},
{
path:'phone',
name:'手机',
component: ()=>import('@/views/electronics/children/phone/index.vue'),
meta:{
title:"手机",
showInbreadcrumb:true
}
},
{
path:'tv',
name:'电视',
component: ()=>import('@/views/electronics/children/tv/index.vue'),
meta:{
title:"电视",
showInbreadcrumb:true
}
}
]
},
//服装鞋帽
{
path:'/clothing',
name:'服装鞋帽',
component: ()=>import('@/views/layout/index.vue'),
redirect: '/clothing/tops',
meta:{
title:"服装鞋帽",
showInbreadcrumb:true
},
children:[
{
path:'tops',
name:'上装',
component: ()=>import('@/views/clothing/children/tops/index.vue'),
meta:{
title:"上装",
showInbreadcrumb:true
}
},
{
path:'lower',
name:'下装',
component: ()=>import('@/views/clothing/children/lower/index.vue'),
meta:{
title:"下装",
showInbreadcrumb:true
}
},
{
path:'shoes',
name:'鞋子',
component: ()=>import('@/views/clothing/children/shoes/index.vue'),
meta:{
title:"鞋子",
showInbreadcrumb:true
}
}
]
},
//放在最后,当前面所有路由都没匹配到时,会匹配该路由,并重定向到根路由
{
path:'*',
redirect:'/',
meta:{
showInbreadcrumb:false
}
},
]
这里我配置的路由有首页、电子数码、服装鞋帽,这三个是一级路由,其中电子数码和服装鞋帽还有二级路由,在meta中我自定义了数据,showInbreadcrumb用于判断是否显示在面包屑中,title为在面包屑显示的名称
获取路由信息
模板部分:
///src/views/layout/index.vue
{{item.meta.title}}
{{item.meta.title}}
{{item_.meta.title}}
js部分:
export default {
data(){
return{
}
},
computed:{
// 侧边导航数据
routes(){
// 从$router.options中获取所有路由信息并过滤
return this.$router.options.routes.filter((item)=>{
return item.meta.showInbreadcrumb
});
},
// 面包屑数据
breadcrumb(){
// 根据路由配置meta中的showInbreadcrumb字段过滤
let matchedArr = this.$route.matched.filter((item)=>{
return item.meta.showInbreadcrumb}
);
// 因为首页比较特殊,必须一直显示在面包屑第一个,如果没有首页路由信息,手动添加到最前面
if(matchedArr[0].meta.title !== '首页'){
matchedArr.unshift(
{
path:'/home',
meta:{
title:"首页",
showInbreadcrumb:true
}
},
)
}
return matchedArr;
},
}
}
注意:拿到this.$route.matched后,不能在其结果上直接追加然后再过滤,否则会页面错乱并且报错,应该先filter,这样会返回一个新的数组,然后再判断追加首页信息
最终效果