在实际项目中面包屑是非常常见的一个功能,用于切换层级选项
当然有的公司会使用TagsView导航栏,这个后续在做介绍
今天分享一个简易的面包屑组件,这边配合ui库进行封装
- 安装依赖,在main.js中引入
yarn add element-ui
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.config.productionTip = false
Vue.use(ElementUI)
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
- 注册路由信息及关联components组件
const routes = [{
path: '/',
name: 'home',
component: () => import('../views/Home.vue'),
meta: { title: '首页', path: '/' },
children: [{
path: '/A-Business',
component: () => import('../views/A-Business.vue'),
meta: { title: 'A', path: '/A-Business' }
},
{
path: '/B-Extension',
component: () => import('../views/B-Extension.vue'),
meta: { title: 'B', path: '/B-Extension' }
},
{
path: '/C-Management',
component: () => import('../views/C-Management.vue'),
meta: { title: 'C', path: '/C-Management' }
}, {
path: '/D-customer',
component: () => import('../views/D-customer.vue'),
meta: { title: 'D', path: '/D-customer' }
}
]
}]
- 新建vue文件,myBreadcrumb.vue,内部使用el-breadcrumb
<template>
<div>
<el-breadcrumb separator="/">
<el-breadcrumb-item v-for="(item, i) in breadList" :key="i">
<a @click.prevent="handleLink(item)">
{{ item.meta.title }}
</a>
</el-breadcrumb-item>
</el-breadcrumb>
</div>
</template>
<script>
export default {
data () {
return {
breadList: null
}
},
created () {
this.getBreadcrumb()
},
methods: {
handleLink(item) {
const { redirect, meta } = item;
if (redirect) {
this.$router.push(redirect);
return;
}
this.$router.push(meta.path);
},
getBreadcrumb () {
// 包含当前路由的所有嵌套路径片段的路由记录
const matched = this.$route.matched.filter((item) => item.meta && item.meta.title);
// 赋值循环渲染
this.breadList = matched
}
},
watch: {
$route(route) {
// 如果转到重定向页面,不要更新面包屑
if (route.path.startsWith("/redirect/")) {
return;
}
this.getBreadcrumb();
}
},
}
</script>
- 引入myBreadcrumb.vue面包屑组件注册使用即可
<template>
<div>
<!-- <myBreadcrumb /> -->
</div>
</template>
import myBreadcrumb from "@/components/myBreadcrumb.vue";
export default {
name: 'xxx'
components: { myBreadcrumb },
};
欢迎大家评论,如有帮助可以关注+收藏,我会经常更新博客,大家一起讨论学习