在线文件地址
https://github1s.com/PanJiaChen/vue-element-admin/blob/HEAD/src/permission.js
说明
该文件是路由层面权限的控制代码,在main.js中加载,核心功能就是对页面中一些页面的访问做权限控制,比如未登录用户不可访问其他页面,已经登录用户还存在一个权限设置的问题,根据不同用户访问不同的路由配置表,以达到权限管理的母的。
文件目录
src/permission.js
引用文件
main.jsimport './permission' // permission control
组件
进度条 nprogress
详见 文章 nprogress
分析
import router from './router'import store from './store'import { Message } from 'element-ui'import NProgress from 'nprogress' // progress barimport 'nprogress/nprogress.css' // progress bar styleimport { getToken } from '@/utils/auth' // get token from cookieimport getPageTitle from '@/utils/get-page-title'NProgress.configure({ showSpinner: false }) // NProgress Configurationconst whiteList = ['/login', '/auth-redirect'] // no redirect whitelistrouter.beforeEach(async(to, from, next) => {// start progress barNProgress.start()// set page titledocument.title = getPageTitle(to.meta.title)// determine whether the user has logged in 判断用户是否登录const hasToken = getToken()if (hasToken) {if (to.path === '/login') {// if is logged in, redirect to the home pagenext({ path: '/' })NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939} else {// determine whether the user has obtained his permission roles through getInfoconst hasRoles = store.getters.roles && store.getters.roles.length > 0if (hasRoles) {next()} else {try {// get user info// note: roles must be a object array! such as: ['admin'] or ,['developer','editor']const { roles } = await store.dispatch('user/getInfo')// generate accessible routes map based on rolesconst accessRoutes = await store.dispatch('permission/generateRoutes', roles)// dynamically add accessible routesrouter.addRoutes(accessRoutes)// hack method to ensure that addRoutes is complete// set the replace: true, so the navigation will not leave a history recordnext({ ...to, replace: true })} catch (error) {// remove token and go to login page to re-loginawait store.dispatch('user/resetToken')Message.error(error || 'Has Error')next(`/login?redirect=${to.path}`)NProgress.done()}}}} else {/* has no token*/// 未登录 分为白名单与其他路径if (whiteList.indexOf(to.path) !== -1) {// in the free login whitelist, go directlynext()} else {// other pages that do not have permission to access are redirected to the login page. 其他无权访问的页面被重定向到登录页面next(`/login?redirect=${to.path}`)NProgress.done()}}})router.afterEach(() => {// finish progress barNProgress.done()})
流程分析
判断用户是否登录
- 已登录
- 是否是login路径
- 是:重定向到首页
- 否:判断用户是否获得权限角色
- 有:放行
- 无:去获取用户权限角色然后再进行跳转
- 是否是login路径
- 未登录
- 是否在白名单
- 在:跳转
- 不在:跳转到登录页面并携带该页面的参数
- 是否在白名单
HACK
// hack method to ensure that addRoutes is complete// set the replace: true, so the navigation will not leave a history record
