思路:
<1>动态绑定面包屑的路由和名称
<el-breadcrumb-item v-for="item in breads" :key="item.title" :to="{ path: item.path }">
{{item.title}}
</el-breadcrumb-item>
<2>在router里的meta里加入每一个路由的title
<3>装面包屑动态的方法,默认首页:let temp = [{ path: "/home", title: "首页" }],
遍历 this.$route.matched,如果有meta.title,则把这个对象添加到数组temp,最后将temp赋值给breads,最后由breads去实现动态绑定
this. $route获取路由的信息对象,打印出来是这样
this.$route.matched为,与此路由匹配到的路由的信息,这里主要用里面的meta
<4>在一进入页面就要展示,所以在created里调用。切换路由也要调用,利用watch监听路由 的变化
//1.放入面包屑
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item
v-for="item in breads"
:key="item.title"
:to="{ path: item.path }"
>{{item.title}}</el-breadcrumb-item>
</el-breadcrumb>
//2.绑定数据
data() {
return {
//面包屑数据
breads: [{ title: "", path: "" }]
};
//3.在router.index中加入meta{title:}
//销售统计
{
path: "/total",
component: Layout,
redirect: "/total/goods-total",
meta: { title: '销售统计' },
children: [
{
path: "/total/goods-total",
component: () => import("../views/total/GoodsTotal.vue"),
meta: { title: '商品统计' },
},
{
path: "/total/order-total",
component: () => import("../views/total/OrderTotal.vue"),
meta: { title: '订单统计' },
},
]
},
//4.封装函数
methods: {
//面包屑动态的方法
liveBreads() {
let temp = [{ path: "/home", title: "首页" }];//默认首页放第一个
this.$route.matched.forEach(val => {
if (val.meta.title) {
temp.push({ path: val.path, title: val.meta.title });
}
});
this.breads = temp;
},
//5.放在created(),打开页面就调用
created() {
//一进入页面就调用面包屑方法
this.liveBreads();
},
//6.watch监听路由
watch: {
//监听路由发生的改变
//$route.path获取当前路由
"$route.path"() {
this.liveBreads();
}
},