一步步创建一个vue项目(三)
根据路由生成一个侧边栏
大致的样子:
配置想要的路由
比如我的路由文件:router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Layout from '../views/layout/Layout'
const _import = require('./_import_' + process.env.NODE_ENV)
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
redirect: '/dashboard',
component: Layout,
name: '首页',
children: [{
path: 'dashboard',
component: _import('dashboard/index')
}]
},
{
path: '/admin',
component: Layout,
name: '菜单1',
icon: 'form',
children: [{
path: 'index',
component: _import('admin/index'),
name: '菜单1-1'
}]
},
{
path: '/auth',
component: Layout,
name: '菜单2',
icon: 'form',
children: [{
path: 'index',
component: _import('auth/index'),
name: '菜单2-1',
children: [{
path: '1',
component: _import('auth/1'),
name: '菜单2-1-1'
}]
}, {
path: '2',
component: _import('auth/2'),
name: '菜单2-2'
}]
}
]
})
页面的内容可以自己随便写,主要是这个格式是这个样子,然后就是SideBar.vue文件:
<template>
<el-menu
mode="vertical"
unique-opened
theme="dark"
router
:collapse="false"
:default-active="$route.path"
background-color="#304156"
text-color="#bfcbd9"
active-text-color="#409EFF"
>
<sidebar-item></sidebar-item>
</el-menu>
</template>
<script>
import SidebarItem from './SidebarItem'
export default {
name: 'sidebar',
components: {
SidebarItem },
data () {
return {
}
},
methods: {
}
}
</script>
<style scoped></style>
这个只是一个简单的侧边栏的框,内容在引入的SidebarItem里面:
//SidebarItem.vue
<template>
<div class="menu-wrapper">
<!--$router.options.routes获取router的内容-->
<!-- 循环router,获取第一层item -->
<template v-for="item in $router.options.routes">
<el-submenu :index="item.path" :key="item.path">
<template slot="title">
<span>{
{
item.name }}</span>
</template>
<!-- 循环第二层children获取第三层child -->
<template v-for="child in item.children">
<!-- 判断是否存在第三层,如果存在则显示 -->
<div
v-if="child.children != null && child.children.length > 0"
:key="child.path"
>
<!-- 展示第三层 -->
<el-submenu :index="child.path" :key="child.path">
<template slot="title">{
{
child.name }}</template>
<template v-for="child1 in child.children">
<router-link
v-if="
child1.path != null &&
child1.path.indexOf('http') != 0 &&
child1.path != ''
"
:to="child.path + '/' + child1.path"
:key="child1.path"
>
<el-menu-item :index="child1.path">{
{
child1.name
}}</el-menu-item>
</router-link>
</template>
</el-submenu>
</div>
<!-- 如果第三层不存在则只展示第二层 -->
<div v-else :key="child.path">
<router-link
v-if="
child.path != null &&
child.path.indexOf('http') != 0 &&
child.path != ''
"
:to="item.path + '/' + child.path"
:key="child.name"
>
<el-menu-item :index="child.path">{
{
child.name }}</el-menu-item>
</router-link>
</div>
</template>
</el-submenu>
</template>
</div>
</template>
<script>
export default {
name: 'SidebarItem',
props: {
routes: {
type: Array
}
},
data () {
return {
status: 0
}
}
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped></style>
到此就制作出了一个侧边栏,这只是一个简单的根据index.js文件制作侧边栏,正在学习通过权限动态获取路由,之后会一点点的增加这个系列,当然,我是参考vue-elementUI-admin这个项目的,本人小白一个,靠自己一点点研究,如有错误请见谅。