(vue权限管理)前端路由表角色权限管理,通过登录不同角色侧边栏显示对应页面

前端路由表角色权限管理,通过登录不同角色侧边栏显示对应页面

demo根据vue-admin-template为基础修改,首先展示实现的效果

在这里插入图片描述

1. 首先在src/router/index.js中添加路由表,其中constantRoutes 设置的为所有角色可见的路由,asyncRouterMap为对应权限人员可见路由,demo路由表代码如下:

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

//避免导航守卫报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
/* Layout */
import Layout from '@/layout'

//所有人可见
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index'),
        meta: {
          title: '首页',
          icon: 'dashboard'
        }
      }
    ]
  },

  {
    path: '/example',
    component: Layout,
    children: [
      {
        path: 'index',
        name: 'Table',
        component: () => import('@/views/table/index'),
        meta: {
          title: '所有人可见',
          icon: 'table'
        }
      }
    ]
  },
  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]

//相应权限人员可见
export const asyncRouterMap = [
  {
    path: '/form',
    component: Layout,
    children: [
      {
        path: 'index',
        name: 'Form',
        component: () => import('@/views/form/index'),
        meta: {
          title: '所有人可见',
          icon: 'form',
          role: ['admin']
        }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: 'system/test',
    name: 'System',
    alwaysShow: true,
    meta:{title:'系统管理', icon: 'nested', role: ['admin','editor']},
    children: [
      {
        path: '权限管理',
        name: 'test',
        name: 'Test',
        component: () => import('@/views/system/index'),
        meta: {
          title: '权限修改',
          icon: 'table',
          role: ['admin']
        }
      }
    ]
  }
]

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  })

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router

2.在src/api/user.js中创建用户登录,获取用户信息,以及登出的接口

在这里插入图片描述

3.在store/modules/user.js文件,添加获取角色权限role的信息

在这里插入图片描述
在这里插入图片描述

4.在src/store/modules/目录下创建permission.js,来存储不同权限动态添加的路由表,文件代码如下:

import { asyncRouterMap, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param role
 * @param route
 */
function hasPermission(role, route) {
    if (route.meta && route.meta.role) {
        // return roleArr.some(role => route.meta.role.includes(role))  //当给的角色权限为数组形式可采取该方式判断返回值
        return route.meta.role.includes(role)?true:false  //当角色权限为字符串时,采用该方式判断
    } else {
        return true
    }
}

/**
 * 将符合相应权限的路由表筛选出来
 * @param routes asyncRouterMap
 * @param role
 */
export function filterasyncRouterMap(routes, role) {
    const res = []
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(role, tmp)) {
            console.log(111);
            if (tmp.children) {
                tmp.children = filterasyncRouterMap(tmp.children, role)
            }
            res.push(tmp)
        }
    })

    return res
}

const permission = {
    state: {
        routes: [],
        addRoutes: []
    },
    mutations: {
        SET_ROUTES: (state, routes) => {
            state.addRoutes = routes
            state.routes = constantRoutes.concat(routes)
        }
    },
    actions: {
        generateRoutes({ commit }, role) {
            return new Promise(resolve => {
                let accessedRoutes
                //如果角色是admin
                if (role.includes('admin')) {
                //将route.js中的admin权限人员可见的路由表加入,此处我们只有admin和editor两个角色
                    accessedRoutes = asyncRouterMap || []
                } else {
                    accessedRoutes = filterasyncRouterMap(asyncRouterMap, role) || []
                }
                commit('SET_ROUTES', accessedRoutes)
                resolve(accessedRoutes)
            })
        }
    }

}

export default permission

5.在src/store/getters.js中,代码如下(注意:state.permission.routes别写成了state.user.routes):

在这里插入图片描述

6.在src/store/index.js中,代码如下

在这里插入图片描述

7.最后在src/permission.js的路由导航守卫中添加动态路由,此处用到了vue-router的addRoute函数,修改处代码如下:

在这里插入图片描述

8.在src/layout/components/Sidebar/index中,添加新的路由表,代码如下:

在这里插入图片描述

最终可以实现文章首部动图效果,简单的记录下前端路由表权限管理功能实现,若有不正确处,评论处可交流讨论,文末会贴源码,安装依赖后可直接运行。

文末demo码云链接:权限管理demo

  • 18
    点赞
  • 127
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
Vue3 中实现权限管理,可以使用路由守卫来限制用户访问某些路由。对于不同的账号角色,可以在登录后将其角色信息保存在 Vuex 状态管理器中,然后在路由守卫中根据角色信息来判断用户是否有权限访问该路由。 以下是基本的实现步骤: 1. 在 Vuex 状态管理器中定义一个用来保存当前登录用户角色信息的状态。 ``` // store.js import { createStore } from 'vuex' const store = createStore({ state: { userRole: '' // 当前用户角色 }, mutations: { setUserRole (state, role) { state.userRole = role } }, actions: { login ({ commit }, { username, password }) { // 登录逻辑,获取用户角色信息 const role = 'admin' commit('setUserRole', role) } } }) export default store ``` 2. 在需要进行权限控制的路由上设置 meta 属性,用来记录该路由需要的权限信息。 ``` // router.js import { createRouter, createWebHistory } from 'vue-router' import Home from './views/Home.vue' import Admin from './views/Admin.vue' const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/admin', name: 'Admin', component: Admin, meta: { requiresAuth: true, // 需要登录才能访问 roles: ['admin'] // 只有管理员角色才能访问 } } ] const router = createRouter({ history: createWebHistory(), routes }) export default router ``` 3. 在路由守卫中根据用户角色信息和路由的 meta 信息来判断用户是否有权限访问该路由。 ``` // router.js import router from './router' import store from './store' router.beforeEach((to, from, next) => { const userRole = store.state.userRole const requiresAuth = to.meta.requiresAuth const roles = to.meta.roles if (requiresAuth && !userRole) { // 如果需要登录且用户未登录,则跳转到登录页 next('/login') } else if (requiresAuth && roles.indexOf(userRole) === -1) { // 如果需要特定角色才能访问,且用户角色不在指定角色列表中,则跳转到首页 next('/') } else { // 其他情况允许访问 next() } }) ``` 这样就可以根据用户角色信息和路由 meta 信息来限制用户访问某些路由了。当用户登录成功后,可以通过 Vuex 的 `setUserRole` 方法来更新用户角色信息,从而控制路由访问权限

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

deku-yzh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值