便于对用户权限进行控制,后台的菜单可以做成动态。
在/src/layout/components/Sidebar/index.vue文件中就行修改
<template>
<div :class="{'has-logo':showLogo}">
<logo v-if="showLogo" :collapse="isCollapse" />
<el-scrollbar wrap-class="scrollbar-wrapper">
<el-menu
:default-active="activeMenu"
:collapse="isCollapse"
:background-color="variables.menuBg"
:text-color="variables.menuText"
:unique-opened="false"
:active-text-color="variables.menuActiveText"
:collapse-transition="false"
mode="vertical"
>
<!--<sidebar-item v-for="route in routes" :key="route.path" :item="route" :base-path="route.path" />-->
<sidebar-item v-for="route in requestMenus" :key="route.path" :item="route" :base-path="route.path" />
</el-menu>
</el-scrollbar>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/styles/variables.scss'
import {userMenu} from "@/api/user";
import Layout from "@/layout/index";
export default {
components: { SidebarItem, Logo },
data() {
return {
requestMenus: []
}
},
created() {
// 获取菜单路由数据
userMenu().then(res => {
const routeList = []
this.handleMenu(routeList, res)
// 首页公共
routeList.unshift(
{
path: '/',
component: Layout,
children: [
{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: { title: '首页', icon: 'dashboard' }
}
]
})
this.$set(this, 'requestMenus', routeList)
})
},
computed: {
...mapGetters([
'sidebar'
]),
routes() {
return this.$router.options.routes
},
activeMenu() {
const route = this.$route
const { meta, path } = route
// if set path, the sidebar will highlight the path you set
if (meta.activeMenu) {
return meta.activeMenu
}
return path
},
showLogo() {
return this.$store.state.settings.sidebarLogo
},
variables() {
return variables
},
isCollapse() {
return !this.sidebar.opened
}
},
methods: {
handleMenu(list , data) {
if (data.length > 0) {
data.forEach(item => {
const menu = {}
if (item.is_leaf === 0) { // 目录
menu.path = '/' + item.code,
menu.redirect = '/' + item.code + '/list',
menu.name = item.code,
menu.meta = {
title: item.title,
icon: item.icon
},
menu.children = []
} else { // 菜单
menu.path = item.code,
menu.name = item.code,
menu.meta = {
title: item.title,
icon: item.icon
}
}
if (item.children && item.children.length > 0) {
this.handleMenu(menu.children, item.children)
}
list.push(menu)
})
}
}
}
}
</script>
注:
- 获取的动态的菜单路由数据必须是在/src/router/index.js文件中已经配置好的
获取的数据格式
[
{
"code":"example",
"title":"EXample",
"icon":"el-icon-s-help",
"children":[
{
"code":"table",
"title":"Table",
"icon":"table",
},
{
"code":"tree",
"title":"Tree",
"icon":"tree",
}
]
}
]