簡單的來講,麪包屑導航的做用就是告訴用戶他們在網站中的位置,方便用戶肯定下一步去留,對於用戶來講這是很好的體驗。javascript
須要手動配置路由和菜單。css
const routes = [
{
path: '/home1',
name: 'home1',
meta: {
breadID: '0'
}
},
{
path: '/home2',
name: 'home2',
meta: {
breadID: '0-0'
}
},
{
path: '/home3',
name: 'home3',
meta: {
breadID: '0-0-0'
}
},
{
path: '/home4',
name: 'home4',
meta: {
breadID: '1'
}
},
{
path: '/home5',
name: 'home5',
meta: {
breadID: '1-0'
}
},
{
path: '/home6',
name: 'home6',
meta: {
breadID: '1-0-0'
}
}
]
複製代碼
麪包屑導航有一個層級的菜單。html
let breadNavList = [
{
id:"0",
name:'0-第一級',
url:'/home1',
menu:[
{
id:'0-0',
name:'0-第二級',
url:'/home2',
menu:[
{
id:'0-0-0',
name:'0-第三級',
url:'/home3',
}
]
}
]
},
{
id:"1",
name:'1-第一級',
url:'/home3',
menu:[
{
id:'1-0',
name:'0-第二級',
url:'/home4',
menu:[
{
id:'1-0-0',
name:'0-第三級',
url:'/home5',
}
]
}
]
}
]
複製代碼
能夠看到在路由的meta
字段中加入了屬性breadID
,詳情解說一下這個屬性java
breadID代表當前路由在menu菜單中的位置。git
'0' 當前麪包屑有一級,0表明該路由在在菜單欄中的位置breadNavList[0]
'0-0' 表明當前麪包屑有兩級,breadNavList[0].menu[0]
'0-0-0' 表明當前麪包屑有三級,breadNavList[0].menu[0].menu[0]
'0-1-0' 表明當前麪包屑有三級,breadNavList[0].menu[1].menu[0]
.....以此類推
複製代碼
數組bread
用來裝載須要展示的路由。如:github
bread = ['第一級','第二級','第三級']
bread = ['第一級','第二級']
複製代碼
效果:npm
第一級 > 第二級 > 第三級
第一級 > 第二級
複製代碼
當路由變化的時候,麪包屑也會發生變化。數組
watch:{
'$route':{
handler(){
this.bread = []
if(this.$route && this.$route.meta && this.$route.meta.breadID){
let arr = this.$route.meta.breadID.split('-')
this.getBread(arr,this.breadNavList)
} else {
console.error('字段`this.$route.meta.breadID`沒有設置')
}
},
immediate:true
}
}
複製代碼
getBread參數:bash
思路:函數
getBread(arr,menu){
if(arr.length < 0){
return;
}
this.bread.push(menu[arr[0]])
menu = menu[arr[0]].menu
arr.shift()
this.getBread(arr,menu)
}
複製代碼
<template>
<div class="bread-wrap">
<div class="bread-item" v-for="(item,index) in bread" :key="index">
<span @click="toBreadRouter(item)">{{item.name}}</span><i v-if="index !== bread.length - 1"> > </i></div>
</div>
</template>
<script> export default { name: "breadNav", data() { return { bread:[],//麪包屑容器 breadNavList:[]// 麪包屑菜單 } }, watch:{ '$route':{ handler(){ this.bread = [] if(this.$route && this.$route.meta && this.$route.meta.breadID){ let arr = this.$route.meta.breadID.split('-') this.getBread(arr,this.breadNavList) } else { console.error('字段`this.$route.meta.breadID`沒有設置') } } } }, methods: { getBread(arr,menu){ if(arr.length > 0){ this.bread.push(menu[arr[0]]) menu = menu[arr[0]].menu arr.shift() if(arr.length > 0){ return this.getBread(arr,menu) } } }, toBreadRouter(item){ this.$emit('changeRoute',item) } } } </script>
<style scoped> .bread-wrap{ color:#606266; font-size:14px; } .bread-wrap .bread-item{ display: inline-block; } .bread-wrap .bread-item span:hover{ cursor: pointer; color:#409EFF; } .bread-wrap .bread-item:last-child{ cursor: auto; color:#303133; } .bread-wrap .bread-item:last-child span{ cursor: auto; } .bread-wrap .bread-item i{ font-style: normal; } </style>
複製代碼
該面包屑組件封裝上了npm有興趣的能夠下載試試看。gitHub地址-麪包屑導航使用教程