首先,权限管理⼀般需求是两个:⻚⾯权限和按钮权限。
- 权限管理⼀般需求是⻚⾯权限和按钮权限的管理
- 具体实现的时候分后端和前端两种⽅案:
前端⽅案会把所有路由信息在前端配置,通过路由守卫要求⽤户登录,⽤户登录后根据⻆⾊过滤出路由表。⽐如我会配置⼀个 asyncroutes 数组,需要认证的⻚⾯在其路由的 meta 中添加⼀个 roles 字段,等获取⽤户⻆⾊之后取两者的交集,若结果不为空则说明可以访问。此过滤过程结束,剩下的路由就是该⽤户能访问的⻚⾯,最后通过 router.addroutes(accessroutes) ⽅式动态添加路由即可。
后端⽅案会把所有⻚⾯路由信息存在数据库中,⽤户登录的时候根据其⻆⾊查询得到其能访问的所有⻚⾯路由信息返回给前端,前端再通过 addroutes 动态添加路由信息。
按钮权限的控制通常会实现⼀个指令,例如 v-permission ,将按钮要求⻆⾊通过值传给v-permission指令,在指令的 moutned 钩⼦中可以判断当前⽤户⻆⾊和按钮是否存在交集,有则保留按钮,⽆则移除按钮。
- 纯前端⽅案的优点是实现简单,不需要额外权限管理⻚⾯,但是维护起来问题⽐较⼤,有新的⻚⾯和⻆⾊需求 就要修改前端代码重新打包部署;服务端⽅案就不存在这个问题,通过专⻔的⻆⾊和权限管理⻚⾯,配置⻚⾯ 和按钮权限信息到数据库,应⽤每次登陆时获取的都是最新的路由信息,可谓⼀劳永逸!
路由守卫 permission.js:
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 bar nprogress.start() // set page title document.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 page next({ path: '/' }) nprogress.done() // hack: https://github.com/panjiachen/vue-element-admin/pull/2939 } else { // determine whether the user has obtained his permission roles through getinfo const hasroles = store.getters.roles && store.getters.roles.length > 0 if (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 roles const accessroutes = await store.dispatch('permission/generateroutes', roles) // dynamically add accessible routes router.addroutes(accessroutes) // hack method to ensure that addroutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await 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 directly next() } 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 bar nprogress.done()})复制代码
路由⽣成## permission.js:
import { asyncroutes, constantroutes } from '@/router'/** * use meta.role to determine if the current user has permission * @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 }}/** * filter asynchronous routing tables by recursion * @param routes asyncroutes * @param roles */export function filterasyncroutes(routes, roles) { const res = [] routes.foreach(route => { const tmp = { ...route } if (haspermission(roles, tmp)) { if (tmp.children) { tmp.children = filterasyncroutes(tmp.children, roles) } res.push(tmp) } }) return res}const state = { routes: [], addroutes: []}const mutations = { set_routes: (state, routes) => { state.addroutes = routes state.routes = constantroutes.concat(routes) }}const actions = { generateroutes({ commit }, roles) { return new promise(resolve => { let accessedroutes if (roles.includes('admin')) { accessedroutes = asyncroutes || [] } else { accessedroutes = filterasyncroutes(asyncroutes, roles) } commit('set_routes', accessedroutes) resolve(accessedroutes) }) }}export default { namespaced: true, state, mutations, actions}复制代码
动态追加路由## permission.js:
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 bar nprogress.start() // set page title document.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 page next({ path: '/' }) nprogress.done() // hack: https://github.com/panjiachen/vue-element-admin/pull/2939 } else { // determine whether the user has obtained his permission roles through getinfo const hasroles = store.getters.roles && store.getters.roles.length > 0 if (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 roles const accessroutes = await store.dispatch('permission/generateroutes', roles) // dynamically add accessible routes router.addroutes(accessroutes) // hack method to ensure that addroutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await 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 directly next() } 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 bar nprogress.done()})复制代码
服务端返回的路由信息如何添加到路由器中?
// 前端组件名和组件映射表const map = { // xx: require('@/views/xx.vue').default // 同步的⽅式 xx: () => import('@/views/xx.vue') // 异步的⽅式 } // 服务端返回的 asyncroutes const asyncroutes = [ { path: '/xx', component: 'xx', ... } ] // 遍历asyncroutes,将component替换为map[component]function mapcomponent(asyncroutes) { asyncroutes.foreach(route => { route.component = map[route.component]; if(route.children) { route.children.map(child => mapcomponent(child)) } }) } mapcomponent(asyncroutes)
ag凯发k8国际的版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。