本文主要将前端部分,后端部分点这里。
如何实现在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,和前端定义好的路由表进行对比,动态加载匹配的路由表。
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'),
meta: { title: 'Form', icon: 'form' }
}
]
},
]
//异步挂载的路由
//动态需要根据权限加载的路由表
export const asyncRouterMap = [
{
path: '/nested',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/nested/menu1/index'),
name: 'nested',
meta: {role:['admin'], title: '超级权限控制测试', icon: 'nested'}
}
]
},
{
path: '/super',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/views/nested/menu1/index'),
name: 'nested',
meta: { title: '普通权限', icon: 'nested'}
}
]
},
{ path: '*', redirect: '/404', hidden: true }
// 404 page must be placed at the end !!!
];
const createRouter = () => new Router({
// mode: 'history', // require service support
scrollBehavior: () => ({ y: 0 }),
routes: constantRouterMap
})
const router = createRouter()
// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
const newRouter = createRouter()
router.matcher = newRouter.matcher // reset router
}
export default new Router({
routes: constantRouterMap
});
主要作用是把后台获取到的role与router/index.js
下asyncRouterMap中的权限信息进行对比
代码如下:
// store/permission.js
import {asyncRouterMap, constantRouterMap} from '@/router'
function hasPermission(roles, route) {
if (route.meta && route.meta.role) {
return roles.some(role => route.meta.role.indexOf(role) >= 0)
} else {
return true
}
}
const permission = {
state: {
routers: constantRouterMap,
addRouters: []
},
mutations: {
SET_ROUTERS: (state, routers) => {
state.addRouters = routers;
state.routers = constantRouterMap.concat(routers);
}
},
actions: {
GenerateRoutes({ commit }, data) {
return new Promise(resolve => {
const { roles } = data;
// console.log(roles)
// console.log(roles.indexOf('admin'))
const accessedRouters = asyncRouterMap.filter(v => {
if (roles.indexOf('admin') >= 0) return true;
if (hasPermission(roles, v)) {
if (v.children && v.children.length > 0) {
v.children = v.children.filter(child => {
if (hasPermission(roles, child)) {
return child
}
return false;
});
return v
} else {
return v
}
}
return false;
});
commit('SET_ROUTERS', accessedRouters);
resolve();
})
}
}
};
export default permission;
在获取完用户的信息之后动态添加有权限的页面。就是调用GenerateRoutes进行对比。
代码如下:
// get user info
await store.dispatch('user/getInfo')
const roles = store.getters.role;
store.dispatch('GenerateRoutes', { roles }).then(() => { // 生成可访问的路由表
router.addRoutes(store.getters.routers) // 动态添加可访问路由表
next({ ...to, replace: true })
})
const store = new Vuex.Store({
modules: {
app,
settings,
user,
permission
},
getters
})
const getters = {
sidebar: state => state.app.sidebar,
device: state => state.app.device,
token: state => state.user.token,
avatar: state => state.user.avatar,
name: state => state.user.name,
role:state=>state.user.role,
routers:state=>state.permission.routers
}
export default getters
在获取到用户信息的时候把role存起来在src/permissions.js
中调用 可以回去看代码中有一句const roles = store.getters.role;
获取到role后和路由表对比。主要看getInfo()中的代码,因为我后端返回的role信息在roleItem.name中,所以先解构了roleItem然后取role。返回的数据中的Data结构如下:
{
"id": 7,
"name": "admin",
"password": "e10adc3949ba59abbe56e057f20f883e",
"avatar": "https://xxxx.com/f778738c-e4f8-4870-cafe.gif",
"roleId": 1,
"roleItem": {
"id": 1,
"name": "admin",
"describe": "管理员具有所有权限"
}
}
语句const role=roleName.split(',')
的作用主要是因为我后端返回的role获取到的是字符串,而前端要求的是数组,把字符串转成数组再进行路由表权限的对比才不会报错。你也可以在后端返回数组。
//store/modules/user.js
import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
return {
token: getToken(),
name: '',
avatar: '',
role:[] //添加了这个
}
}
const state = getDefaultState()
const mutations = {
RESET_STATE: (state) => {
Object.assign(state, getDefaultState())
},
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
//state.role的提交
SET_ROLE:(state, role)=>{
state.role = role
}
}
const actions = {
// user login
login({ commit }, userInfo) {
const { username, password } = userInfo
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => {
const { token } = response
commit('SET_TOKEN', token)
setToken(token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// get user info
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const { data } = response
if (!data) {
return reject('Verification failed, please Login again.')
}
const { name, avatar ,roleItem} = data
const roleName =roleItem.name
//因为后端返回的是字符串,这里把字符串转换为数据配合权限验证
const role=roleName.split(',')
commit('SET_ROLE',role)
commit('SET_NAME', name)
commit('SET_AVATAR', avatar)
resolve(data)
}).catch(error => {
reject(error)
})
})
},
// user logout
logout({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
removeToken() // must remove token first
resetRouter()
commit('RESET_STATE')
window.location.reload()
resolve()
}).catch(error => {
reject(error)
})
})
},
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
removeToken() // must remove token first
commit('RESET_STATE')
resolve()
})
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
后端是先通过login()接口验证账号密码是否正确,正确后返回token给前端,前端再调用getinfo()发送请求,后端通过请求头中携带的token获取用户信息,token中存放用户的部分信息后端通过获取token中的信息再进行数据的查询。如token中存放了用户的ID,后端通过获取到token再从token中获取ID,进行数据的查询。注意后端获取token的时候如果你未修改utils/request.js
中的参数,headers中存放token的是X-token 你也可以修改 config.headers['X-Token'] = getToken()
中的参数。
看不懂的可以多看几遍花裤衩大佬的文章,三遍不懂六遍就能自己改了。