最近遇到一个项目, 设计图他的导航菜单是这样式的
布局很简单, 复制element-ui的布局容器稍微改一下就行了
之前的话, 我的导航菜单都是固定写死的, 这次想通过配置router meta属性来控制导航菜单的内容.
一级导航
然后在页面上, 可以通过
this.$router.options.routes[0].children 来取到路由数据再在组件中渲染出来
data(){
return{
active:'homePage',
routerList:[]
}
},
mounted() {
let data = this.$router.options.routes[0].children;
data.forEach(item => {
let row = {};
item.meta && (row = item.meta);
item.meta && item.children && (row.chaildren = item.children);
!this.$util.isEmpty(row) && this.routerList.push(row);
})
console.log(this.routerList)
},
<el-menu-item :index="item.path" :class="item.path === $route.path ? 'm-active' : ''" v-for="(item,index) in routerList" :key="index">
<i class="el-icon-setting"></i>
<span slot="title">{{ item.name }}</span>
</el-menu-item>
处理后的结果
后续添加只需要在router 下面index.js里面配置meta
二级导航
设计图上是左右布局的有二级导航,所以在第一级导航的点击事件里面封装二级导航的数据。
router index.js 二级导航的meta属性配置:
parentTitle这个属性处理二级导航的一个分组。没有则不分组
//第一级别菜单点击事件
firstLevelNavigation(item){
if(!item.chaildren)return;
console.log(item);
this.routerList = []; //二级导航的数据
let tempArr = [];
//这一步循环把所有对象的meta对象取出来组成新数组
item.chaildren.forEach(it =>{
let row = {};
it.meta && (row = it.meta);
it.meta && tempArr.push(row);
})
console.log(tempArr,'子菜单数据');
tempArr = this.routerMap([...tempArr]);
//防止有重复的去重,
//tempArr = this.$util.deduplicationObj(tempArr);
this.routerList = tempArr;
//console.log(this.routerList,'组装后')
},
//routermap
routerMap(arr){
let parentTitles = [];
let children = [];
let result = [];
//获取到arr所有有parentTitle 的item
arr.forEach(item => {
if(item.parentTitle){
parentTitles.push(item.parentTitle);
children.push(item);
}else{
result.push(item);
}
});
parentTitles.forEach(item => {
let row = {children:[]};
children.forEach(key => {
if(item === key.parentTitle){
row.name = item;
row.path = '';
row.children.push(key);
}
})
result.push(row);
})
console.log(children, parentTitles, result);
return result;
},
组装后测试打印:
大概就是这样的结构,,再把这个数组放在二级导航栏去循环,渲染起来就很方便了。
<div v-for="(item,index) in routerList" :key="index">
<!--二级菜单分类-->
<el-submenu index="1" v-if="item.children">
<template slot="title">
<span>{{ item.name }}</span>
</template>
<el-menu-item :index="itemChildrenRow.path"
:class="$route.path === itemChildrenRow.path ? 'm-active' : ''"
v-for="(itemChildrenRow,index) in item.children" :key="index">
{{ itemChildrenRow.name }}
</el-menu-item>
</el-submenu>
<!--不分类-->
<el-menu-item v-if="!item.children" :index="item.path"
:class="$route.path === item.path ? 'm-active' : ''">
<span slot="title">{{ item.name }}</span>
</el-menu-item>
</div>
再测试一个分组的二级导航和不分组的