vue项目权限管理(vue项目权限控制)

首先,权限管理⼀般需求是两个:⻚⾯权限和按钮权限。

  1. 权限管理⼀般需求是⻚⾯权限和按钮权限的管理
  2. 具体实现的时候分后端和前端两种⽅案:

前端⽅案会把所有路由信息在前端配置,通过路由守卫要求⽤户登录,⽤户登录后根据⻆⾊过滤出路由表。⽐如我会配置⼀个 asyncRoutes 数组,需要认证的⻚⾯在其路由的 meta 中添加⼀个 roles 字段,等获取⽤户⻆⾊之后取两者的交集,若结果不为空则说明可以访问。此过滤过程结束,剩下的路由就是该⽤户能访问的⻚⾯,最后通过 router.addRoutes(accessRoutes) ⽅式动态添加路由即可。

后端⽅案会把所有⻚⾯路由信息存在数据库中,⽤户登录的时候根据其⻆⾊查询得到其能访问的所有⻚⾯路由信息返回给前端,前端再通过 addRoutes 动态添加路由信息。

按钮权限的控制通常会实现⼀个指令,例如 v-permission ,将按钮要求⻆⾊通过值传给v-permission指令,在指令的 moutned 钩⼦中可以判断当前⽤户⻆⾊和按钮是否存在交集,有则保留按钮,⽆则移除按钮。

  1. 纯前端⽅案的优点是实现简单,不需要额外权限管理⻚⾯,但是维护起来问题⽐较⼤,有新的⻚⾯和⻆⾊需求 就要修改前端代码重新打包部署;服务端⽅案就不存在这个问题,通过专⻔的⻆⾊和权限管理⻚⾯,配置⻚⾯ 和按钮权限信息到数据库,应⽤每次登陆时获取的都是最新的路由信息,可谓⼀劳永逸!

路由守卫 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)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

(0)
上一篇 2022年12月3日 上午9:56
下一篇 2022年12月3日 上午9:58

相关推荐

  • erp工程管理软件

    erp工程管理软件概述 ERP(Enterprise Resource Planning)工程管理软件是一种用于企业资源规划的应用程序,可以帮助企业实现其业务流程和信息系统的集成。…

    科研百科 2025年1月2日
    1
  • 协同办公系统首页

    协同办公系统首页 随着现代企业越来越注重效率和团队协作,协同办公系统已经成为许多企业的必备工具。协同办公系统的作用在于提供一个集中的平台,帮助企业管理者实现信息共享、任务分配、日程…

    科研百科 2024年8月25日
    35
  • 足浴门店管理软件为会员消费开单、收银、支付一码搞定?(足疗店收银系统免费版)

    足浴店管理软件系统赋予实体足浴门店信息化管理能力,能够帮助足浴门店完善具体的会员营销管理工作,对会员属性进行标签分组,实现足浴门店日常对会员进行差异化服务营销,刺激会员进店复购下单…

    科研百科 2022年12月28日
    206
  • 强化主体责任落实 提升行业安全素质——各地住房和城乡建设系统“安全生产月”活动启幕

    今年6月是第21个全国“安全生产月”,主题是“遵守安全生产法当好第一责任人”。连日来,湖北、山东、江苏、陕西等地住房和城乡建设主管部门及有关单位陆续启动“安全生产月”活动,并结合本…

    科研百科 2022年7月24日
    212
  • 沙漠变绿洲科研项目

    沙漠变绿洲科研项目 沙漠是地球上最荒凉的地区之一,也是人类面临的严重挑战之一。每年有大量的沙漠土地被沙漠化,造成了大量的土地损失和水资源的短缺。为了解决这个问题,世界各地都在开展各…

    科研百科 2025年3月23日
    1
  • 深圳报考项目管理

    深圳报考项目管理 随着深圳经济的快速增长,项目管理已经成为了一个热门的行业。深圳作为一个现代化的城市,拥有着完善的基础设施和良好的市场环境,因此项目管理在深圳也成为了一个不可或缺的…

    科研百科 2024年7月16日
    69
  • 三峡工程项目管理

    三峡工程项目管理 三峡工程项目是中国历史上最大的水利工程之一,也是中国工程史上的里程碑。该工程包括三峡水电站、三峡船闸、库区移民等 components。三峡工程项目的管理是这个项…

    科研百科 2024年8月21日
    41
  • 井下变电所科研项目

    井下变电所科研项目 在现代化的电力系统中,井下变电所是一个非常重要的组成部分。它为煤矿企业提供稳定的电力供应,保障企业的正常运转。然而,随着煤矿行业的不断发展,井下变电所面临着越来…

    科研百科 2025年4月22日
    0
  • 烟台市委统战部机关第一党支部:围绕3个“1+1” 育亮点 夯基础 强队伍

    编者按 为充分发挥先进典型的示范引领作用,以点带面、辐射带动基层党支部建设水平整体提升,根据市委组织部通知要求,市委市直机关工委组织所属各级党组织开展烟台市市级样板党支部推荐和市直…

    科研百科 2023年9月28日
    170
  • 科研项目批准号如何查找

    科研项目批准号是科研项目的重要标识符,能够证明该项目在法律上的存在和实施。因此,对于任何研究人员来说都是非常重要的。 那么,如何查找科研项目的批准号呢?以下是一些基本的步骤: 1….

    科研百科 2025年2月4日
    9