在實際項目中麵包屑是非常常見的一個功能,用於切換層級選項 當然有的公司會使用TagsView導航欄,這個後續在做介紹 今天分享一個簡易的麵包屑組件,這邊配合ui庫進行封裝 安裝依賴,在main.js中引入 yarn add element-ui import Vue from 'vue' impor ...
在實際項目中麵包屑是非常常見的一個功能,用於切換層級選項
當然有的公司會使用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 },
};
歡迎大家評論,如有幫助可以關註+收藏,我會經常更新博客,大家一起討論學習