Vue + Element UI实现权限管理系统

本文以Element UI为例,介绍如何使用vue + Element UI实现后台管理系统的权限管理控制。

1在路由router.js里面声明权限为admin的路由(异步挂载的路由asyncRouterMap)

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

/* Layout */
import Layout from '@/views/layout/Layout'

export const constantRouterMap = [
// 登录
{
path: '/login',
name: 'login',
component: () => import('@/views/login/login')
},
{
path: '/404',
component: () => import('@/views/errorPage/404'),
},
{
path: '',
redirect: '/login',
},
]

export const asyncRouterMap = [
// 首页
{
path: '/home',
component: Layout,
redirect: '/home/index',
hidden: false,
meta: {
title: '首页',
icon: 'home',
roles: [1]
},
children: [{
path: 'index',
component: () => import('@/views/home/index'),
name: 'home',
hidden: false,
meta: { title: '首页', icon: 'home', noCache: true, roles: ['admin'] }
}]
},
{ path: '*', redirect: '/404', hidden: true }
]

export default new Router({
mode: 'hash',
routes: constantRouterMap
})

constantRouterMap是默认加载的路由表,不需要进行权限验证。
asyncRouterMap是异步加载的路由表,也就是说需要进行权限验证。
roles是一个数组,用来存放当前路由可以访问的权限。
hidden设置boolean值来判断是否在菜单栏渲染。
noCache设置boolean值来判断是否开启vue组件缓存,这里就先不做演示了。
icon用来设置菜单栏图标。

2定义permission.js进行路由拦截,动态添加可访问路由表

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // getToken from localStorage

const whiteList = ['/login', '404']// no redirect whitelist

router.beforeEach((to, from, next) => {
if (getToken()) {
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
} else {
if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
const roles = res.data.roles // note: roles must be a array! such as: ['admin','market']
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
}).catch((err) => {
store.dispatch('FedLogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else {
next()
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
next()
} else {
next('/login') // 否则全部重定向到登录页
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
}
}
})

注意:permission.js一定要在main.js中import

3使用vuex进行权限判断,动态生成对应权限的路由表

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { asyncRouterMap, constantRouterMap } from '@/router'

/**
* 通过meta.role判断是否与当前用户权限匹配
* @param roles
* @param route
*/
function hasPermission(roles, route) {
if (route.meta && route.meta.roles) {
return roles.some(role => route.meta.roles.includes(role))
} else {
return true
}
}

/**
* 递归过滤异步路由表,返回符合用户角色权限的路由表
* @param routes asyncRouterMap
* @param roles
*/
function filterAsyncRouter(routes, roles) {
const res = []

routes.forEach(route => {
const tmp = { ...route }
if (hasPermission(roles, tmp)) {
if (tmp.children) {
tmp.children = filterAsyncRouter(tmp.children, roles)
}
res.push(tmp)
}
})

return res
}

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
let accessedRouters
accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
commit('SET_ROUTERS', accessedRouters)
resolve()
})
}
}
}

export default permission

3使用vuex进行权限判断,动态生成对应权限的路由表

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // getToken from localStorage

const whiteList = ['/login', '404']// no redirect whitelist

router.beforeEach((to, from, next) => {
if (getToken()) {
/* has token*/
if (to.path === '/login') {
next({ path: '/' })
} else {
if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
store.dispatch('GetUserInfo').then(res => { // 拉取user_info
const roles = res.data.roles // note: roles must be a array! such as: ['admin','market']
store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
})
}).catch((err) => {
store.dispatch('FedLogOut').then(() => {
Message.error(err)
next({ path: '/' })
})
})
} else {
next()
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单,直接进入
next()
} else {
next('/login') // 否则全部重定向到登录页
NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
}
}
})

注意:permission.js一定要在main.js中import

3动态渲染菜单栏

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<el-scrollbar wrapClass="scrollbar-wrapper">
<el-menu
mode="vertical"
:show-timeout="200"
:default-active="$route.path"
background-color="#304156"
text-color="#bfcbd9"
active-text-color="#409EFF"
>
<sidebar-item :routes="permission_routers"></sidebar-item>
</el-menu>
</el-scrollbar>
</template>

<script>
import { mapGetters } from 'vuex'
import SidebarItem from './SidebarItem'

export default {
components: { SidebarItem },
computed: {
...mapGetters([
'permission_routers'
])
}
}
</script>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<template>
<div class="menu-wrapper">
<template v-for="(item,index) in routes" v-if="!item.hidden&&item.children">

<router-link v-if="hasOneShowingChildren(item.children) && !item.children[0].children&&!item.alwaysShow" :to="item.path+'/'+item.children[0].path"
:key="item.children[0].name" :class="returnClass(index)">
<el-menu-item :index="item.path+'/'+item.children[0].path">
<svg-icon v-if="item.children[0].meta&&item.children[0].meta.icon" :icon-class="item.children[0].meta.icon"></svg-icon>
<span v-if="item.children[0].meta&&item.children[0].meta.title" slot="title">{{generateTitle(item.children[0].meta.title)}}</span>
</el-menu-item>
</router-link>

<el-submenu v-else :index="item.name||item.path" :key="item.name">
<template slot="title">
<svg-icon v-if="item.meta&&item.meta.icon" :icon-class="item.meta.icon"></svg-icon>
<span v-if="item.meta&&item.meta.title" slot="title">{{generateTitle(item.meta.title)}}</span>
</template>

<template v-for="child in item.children">
<sidebar-item :is-nest="true" class="nest-menu" v-if="child.children&&child.children.length>0&&!child.hidden" :routes="[child]" :key="child.path"></sidebar-item>

<router-link v-else :to="item.path+'/'+child.path" :key="child.name">
<el-menu-item :index="item.path+'/'+child.path">
<svg-icon v-if="child.meta&&child.meta.icon" :icon-class="child.meta.icon"></svg-icon>
<span v-if="child.meta&&child.meta.title" slot="title">{{generateTitle(child.meta.title)}}</span>
</el-menu-item>
</router-link>
</template>
</el-submenu>

</template>
</div>
</template>

<script>
import { generateTitle } from '@/utils/i18n'

export default {
name: 'SidebarItem',
props: {
routes: {
type: Array
}
},
methods: {
returnClass(index){
return "item"+index
},
hasOneShowingChildren(children) {
const showingChildren = children.filter(item => {
return !item.hidden
})
if (showingChildren.length === 1) {
return true
}
return false
},
generateTitle
}
}
</script>
扫一扫,请老师喝水