首先看看element官方的导航代码,参考教程:nav-导航
其他的啥都不说,直接来看代码
可以在components下面创建一个可以复用的组件。
模板部分
实现动态数据的代码,这部分放在组件的<template></template>
标签中,仔细分析一下代码,就知道可以解析一级或者多级菜单。
<div class="nav-list">
<el-row class="tac">
<el-col>
<el-menu
default-active="/"
router
class="el-menu-vertical-demo"
background-color="#545c64"
text-color="#fff"
active-text-color="#ffd04b"
>
<div v-for="(subMenu, subIndex) in navList" :key="subIndex">
<!--只有一级菜单-->
<el-menu-item v-if="!subMenu.children" :index="subMenu.to">
<i class="el-icon-location"></i>
{{ subMenu.title }}
</el-menu-item>
<!-- 多级菜单 -->
<el-submenu v-else :index="subIndex + ''">
<template slot="title">
<i class="el-icon-location"></i>
<span>{{ subMenu.title }}</span>
</template>
<el-menu-item-group>
<el-menu-item
v-for="(menu, index) in subMenu.children"
:index="menu.to"
:key="index"
>
<i class="el-icon-location"></i>
{{ menu.title }}
</el-menu-item>
</el-menu-item-group>
</el-submenu>
</div>
</el-menu>
</el-col>
</el-row>
</div>
首先想让他变成路由导航,
el-menu
一定要添加router
属性,此时他就会根据el-menu-item
中的index
去push router
需要注意的是:多级菜单时,虽然el-submenu
并不想让他跳转,但是一定要加上 index 属性(可以放index就行,保证唯一性)
index 属性的值一定要是 string ,比如这里的 subIndex 就要拼接个 ‘’ ,达到转换字符串的目的
JavaScript - navList部分
data() {
return {
navList: [
{
icon: 'apps',
title: 'Index',
children: [
{
icon: 'apps',
title: 'page1',
to: '/ac'
},
{
icon: 'apps',
title: 'page2',
to: '/'
}
]
},
{ icon: 'assignment', title: 'BKMs', to: '/acb' },
{
icon: 'apps',
title: 'demo',
children: [
{
icon: 'apps',
title: 'demo1',
to: '/accb'
}
]
}
]
}
},
我的 Demo 只有两层,如果需要更多层,继续嵌套就可以了。
基本使用
因为是在components里面的组件,我们可以直接在需要导航的地方直接引用:
<div class="left-nav-box">
<span class="nav-box-title">导航</span>
<sideBar></sideBar>
</div>
动态数据
这里的sideBar
是一个组件,希望可以通过子组件传数据,所以需要用到props
props:{
categoriesVal: {
type: Object,
default : []
}
},
比如这里我想动态的生成分类的菜单,定义了一个categoriesVal,类型是Object,因为分类是个二级菜单,大概会传入下面这个样子的数据:
{ icon: 'assignment', title: 'BKMs', to: '/acb' },
{
icon: 'apps',
title: 'demo',
children: [
{
icon: 'apps',
title: 'demo1',
to: '/accb'
}
]
}
类型可以就是object,最后去页面中push进数组即可。
然后我们在引用sideBar
的子页面准备好动态数据,比如我的:
pushCategories(){
for (let i = 0; i < this.categoriesRes.length; i++) {
this.categories.children.push(
{
icon: '',
title: this.categoriesRes[i].name,
to: this.categoriesRes[i].pinyin
}
)
}
}
data()
中的数据:
categories:
{
icon: 'el-icon-location',
title: '分类',
children: [
]
},
这样子的动态数据就准备好啦,全部都是从数据库中取出来的。
然后需要修改一下引用的地方,我们直接引用组件的时候是这样使用的:
<div class="left-nav-box">
<span class="nav-box-title">导航</span>
<sideBar></sideBar>
</div>
修改为:
<div class="left-nav-box">
<span class="nav-box-title">导航</span>
<sideBar :categories-val = "categories"></sideBar>
</div>
</div>
categories-val
就是组件中定义的props
,驼峰命名就要转换为-
模式。然后等号后面就是我们的动态数据。
然后在组件中,我们只需要
this.navList.push(
this.categoriesVal,
)
暂无评论内容