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年6月9日 上午8:40
下一篇 2022年6月9日 上午8:42

相关推荐

  • 党员e先锋密码设置要求

    党员e先锋密码设置要求 党员e先锋是中国共产党党员在数字化时代的一项任务,也是落实党的数字化建设要求的重要举措。为了确保党员e先锋系统的正常运行,党员必须树立正确的密码观念,设置合…

    科研百科 2024年11月14日
    3
  • 怎么看老师是否带学生做科研项目

    怎么看老师是否带学生做科研项目 在现代社会,科研项目是许多学生和专业人士追求的知识与技能来源。而老师带学生一起做科研项目,则是提高教学质量,帮助学生获得实践经验和知识的重要途径之一…

    科研百科 2024年11月8日
    0
  • 如何利用科研项目管理系统提高项目执行效率?

    科研项目管理系统是确保科研项目顺利完成的重要工具。然而,在实践中,科研项目管理存在许多痛点,包括项目进度难以控制、项目执行效率低下、数据管理混乱、沟通不畅、审批流程不透明和项目管理…

    科研百科 2023年10月5日
    214
  • 深圳路桥项目管理系统

    深圳路桥项目管理系统: 提升项目管理效率的利器 随着深圳路桥项目的不断增多,项目管理的需求也越来越大。传统的手动管理方式已经无法满足现代项目的需求,因此,深圳路桥项目管理系统应运而…

    科研百科 2024年12月17日
    0
  • 商场合同范本(商场合同管理)

    商场合同管理 商场合同管理是商场运营中非常重要的一环,它关系到商场的生死存亡。商场合同管理是指在商场中,对合同进行管理和协调,确保每个合同的有效性和合法性,并且协调各个合同之间的关…

    科研百科 2024年6月4日
    74
  • 硕士如何查询自己参加的项目

    硕士如何查询自己参加的项目硕士如何查询自己参加的项目考试,应该是每年的二模,因为这样的事的实行时间不长,而且一定程度上也是咱们的正式考试,既然考试还有一年,就不要错过了,毕竟高考题…

    科研百科 2024年11月28日
    0
  • 天翎低代码Excel导入导出介绍(天翎软件)

    本文主要介绍了天翎低代码平台的Excel导入导出功能和优势。 1、 导入导出的功能作用 在现代企业中,数据的导入和导出是一项关键任务。然而,传统的Excel导入导出方式常常繁琐且容…

    科研百科 2024年5月16日
    70
  • 中医药科研如何更好发展(中医药科研如何更好发展产业)

    近年来,国家高度重视中医药科研发展,建立国家中医临床研究基地,重新开启国家中医药管理局中医药行业科研专项研究,鼓励以国家中医临床研究基地为研究平台,整合优势资源围绕基地重点病种开展…

    科研百科 2024年6月18日
    70
  • 客户关系管理的系统

    客户关系管理(CRM)系统是帮助企业管理客户信息和业务流程的软件系统。随着现代商业的发展,越来越多的企业开始重视客户关系管理,因为它可以提高客户满意度,增加销售额,减少客户流失率。…

    科研百科 2024年8月26日
    39
  • 三个全光网络系统图,办公网、无线网及智能化专网(全光网络架构图)

    大家好,我是薛哥。最近我们VIP会员群的读者咨询全光网络系统的CAD设计图纸,全光网络最近几年非常的火,很多的弱电项目都在考虑设计全光网络,那么全光网络如何设计呢?它的系统架构如何…

    科研百科 2023年12月1日
    124