文章目录
前言
本文主要将前端部分,后端部分点这里。
如何实现在vue-element-admin中的权限控制花裤衩大佬的教程已经写的很详细,花裤衩实现教程。这里详细记一次自己实现的学习过程。后台用spring boot,模板用 vue-admin-templateGitHub地址
权限控制可以后端实现也可以前端实现,本文主要接受前端控制方法。后端控制在可以直接返回路由表给前端,在获取完用户信息后动态加载,返回的数据格式参考router/index.js
中的样式:
{
path: '/nested',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/nested/menu1/index'),
name: 'nested',
meta: {
role:['admin'], title: '超级权限控制测试', icon: 'nested'}
}
]
}
一、实现思路
拿到后台返回的权限role,和前端定义好的路由表进行对比,动态加载匹配的路由表。
二、前端部分具体实现
1.router/index.js
constantRouterMap 是默认加载的路由表,asyncRouterMap是动态加载的路由表,在后端拿到的role会与asyncRouterMap中的路由表进行对比,然后加载有权限的页面。注意变量名字和下载的模板里的不一样注意修改导出的名字。
代码如下:
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
/* Layout */
import Layout from '@/layout'
/**
* Note: sub-menu only appear when route children.length >= 1
* Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
*
* hidden: true if set true, item will not show in the sidebar(default is false)
* alwaysShow: true if set true, will always show the root menu
* if not set alwaysShow, when item has more than one children route,
* it will becomes nested mode, otherwise not show the root menu
* redirect: noRedirect if set noRedirect will no redirect in the breadcrumb
* name:'router-name' the name is used by <keep-alive> (must set!!!)
* meta : {
roles: ['admin','editor'] control the page roles (you can set multiple roles)
title: 'title' the name show in sidebar and breadcrumb (recommend set)
icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
breadcrumb: false if set false, the item will hidden in breadcrumb(default is true)
activeMenu: '/example/list' if set path, the sidebar will highlight the path you set
}
*/
/**
* constantRoutes
* a base page that does not have permission requirements
* all roles can be accessed
*/
export const constantRouterMap = [
{
path: '/login',
component: () => import('@/views/login/index'),
hidden: true
},
{
path: '/404',
component: () => import('@/views/404'),
hidden: true
},
{
path: '/',
component: Layout,
redirect: '/dashboard',
children: [{
path: 'dashboard',
name: 'Dashboard',
component: () => import('@/views/dashboard/index'),
meta: {
title: 'Dashboard', icon: 'dashboard' }
}]
},
{
path: '/example',
component: Layout,
redirect: '/example/table',
name: 'Example',
meta: {
title: 'Example', icon: 'el-icon-s-help', role: ['super_editor'] },
children: [
{
path: 'table',
name: 'Table',
component: () => import('@/views/table/index'),
meta: {
title: 'Table', icon: 'table' }
},
]
},
{
path: '/ttt',
component: Layout,
children: [
{
path: 'index',
name: 'ttt',
component: () => import('@/views/tree/index'</