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

在路由 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
53
54
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 用来设置菜单栏图标。

定义 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
41
42
43
44
45
46
47
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

使用 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;

使用 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
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

动态渲染菜单栏

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
<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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<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>