1 Star 2 Fork 1

Zihao.Yu/vue_user_permission_demo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
ISC

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

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

ISC License Copyright (c) 2023, Zihao.Yu Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

简介

主要是基于vue-admin-template实现对前端路由表用户权限管理功能实现 展开 收起
JavaScript 等 4 种语言
ISC
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
JavaScript
1
https://gitee.com/zihaoyu/vue_user_permission_demo.git
git@gitee.com:zihaoyu/vue_user_permission_demo.git
zihaoyu
vue_user_permission_demo
vue_user_permission_demo
master

搜索帮助