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

相关推荐

  • 如何制作一份好的作业指导书(标准作业流程)-SOP制作(sop作业指导书怎么制作)

    好的SOP是什么样子 SOP应该是从动作的开始到动作的结束,中间的每一个动作、每一个规格都要有详细的说明,每一种不良现象都要有良品和不良品的图片。 之前生产某客户的的BOSA时,其…

    科研百科 2022年7月4日
    331
  • 高项信息系统项目管理师

    高项信息系统项目管理师 随着信息技术的不断发展,信息系统项目管理师这一职业也越来越受到关注。作为一个专业的项目管理师,高项信息系统项目管理师需要掌握一系列的技能和知识,才能有效地管…

    科研百科 2024年5月31日
    79
  • 考信息系统项目管理师证,有用吗?

    1.国家级证书,双章认证 软考是由国家人力资源和社会保障部、工业和信息化部领导下的国家级考试,信息系统项目管理师证书上有最权威的人社部和工信部双章认证,证书权威性毋庸置疑。 2.增…

    科研百科 2023年12月23日
    144
  • 医学科研项目编号

    科研项目编号:12345 近年来,随着人口老龄化的不断加剧,心血管疾病成为了全球面临的重要健康问题之一。为了深入研究心血管疾病的发生机制和治疗方法,许多医学研究人员进行了大量工作,…

    科研百科 2025年3月20日
    1
  • 福建省人民政府关于印发福建省省级政府投资项目代建制管理办法(试行)的通知

    福建省人民政府关于印发福建省省级政府投资项目代建制管理办法(试行)的通知 闽政〔2023〕2号 各市、县(区)人民政府,平潭综合实验区管委会,省人民政府各部门、各直属机构,各大企业…

    科研百科 2023年10月28日
    121
  • 企业业务流程管理软件

    企业业务流程管理软件 随着企业规模的扩大和业务的复杂性增加,传统的手动业务流程管理已经无法满足现代企业的需要。因此,企业业务流程管理软件成为了现代企业必不可少的工具之一。本文将介绍…

    科研百科 2024年5月24日
    54
  • 南乐县农信联社 理财POS成为揽存利器

    南乐县农信联社 理财POS成为揽存利器 【中原经济网讯】2月份以来,南乐县农信联社念好“强、严、重”三字经,巧借外拓POS理财转账终端,有效吸引他行资源,取得显著成效。截至目前,该…

    科研百科 2022年5月31日
    236
  • top think项目管理系统

    Top Think 项目管理系统:提升企业项目管理效率的利器 随着企业竞争的加剧,项目管理的重要性越来越受到企业的重视。然而,传统的项目管理方法已经无法满足现代企业的需求,因此,一…

    科研百科 2024年12月23日
    3
  • 会计科研立项课题参考(会计方面科研项目申请书怎么写)

    会计方面科研项目申请书的写作步骤如下: 一、项目概述 1. 研究背景:介绍当前会计领域存在的一些问题,如财务信息的准确性、真实性、可靠性等问题。2. 研究目的:明确研究的目的和意义…

    科研百科 2024年8月1日
    48
  • 协同 办公(协同办公办公)

    协同办公办公:让工作更加高效和流畅 随着现代办公方式的不断创新和变化,协同办公办公已经成为了现代企业必须面对的问题。协同办公办公是指通过团队协作和沟通,来实现工作任务的高效完成和顺…

    科研百科 2024年6月4日
    89