Vue后台管理系统菜单及按钮权限实现方式

1,717 阅读1分钟

菜单权限实现

/*
后台返回的权限数据
routes: [
0: "Test",
1: "Test2",
2: "Test3",
...
]*/

import Layout from '@/layout'
// 默认任意用户可以看到的路由组件
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'}
        }]
    }
]
// 重定向 写到路由的最后面
const anyRoutes = {path: '*', redirect: '/404', hidden: true}
// 需要权限的路由
const asyncRoutes = [
    /* 商品管理 */
    {
        name: 'Test',
        path: '/test',
        component: Layout,
        redirect: {name: 'test2'},
        meta: {
            title: '测试',
            icon: 'el-icon-s-shop'
        },
        children: [
            {
                name: 'test2',
                path: 'test2/list',
                component: () => import(/* webpackChunkName: "test2" */ '@/views/product/test2/list'),
                meta: {title: '测试2'}
            },
            {
                name: 'test3',
                path: 'test3/list',
                component: () => import(/* webpackChunkName: "test3" */ '@/views/product/test3/list'),
                meta: {
                    title: '测试3'
                }
            },
    }
]
/**
 * 过滤路由
 * @param asyncRoutes 需要权限路由 
 * @param routeNames:后台返回该用户的权限信息
 * @returns {Promise<void>} 处理后的 asyncRouters 字符串
 */
function handleBaseRouterToRolesRouter (asyncRoutes, routeNames) {
    // 过滤数据
  let routes = asyncRoutes.filter(item => {
    return routeNames.some(r => {
      return r === item.name
    })
  })
  // 递归遍历
  for (const item of routes) {
    if (item.children) {
      item.children = handleBaseRouterToRolesRouter(item.children, routeNames)
    }
  }
  return routes
}

// 通过addRoutes方法完成动态路由
// addRoutes动态添加更多的路由规则  把404添加到最后面 = anyRoutes  
router.addRoutes([...handleBaseRouterToRolesRouter(asyncRoutes,'后台返回的权限数据'), anyRoutes])

按钮权限实现

/*
后台返回该用户的权限信息
[
0: "cuser.detail",
1: "cuser.update",
2: "cuser.delete",
3: "btn.User.add"
...
]
*/
/**
 * 判断当前用户是否有此按钮权限
 * @param {按钮权限字符串} permission
 */
export function hasBtnPermission(permission) {
  // 得到当前用户的所有按钮权限
  const myBtns = store.getters.buttons
  // 如果指定的功能权限在myBtns中, 返回true ==> 这个按钮就会显示, 否则隐藏
  return myBtns.indexOf(permission) !== -1
}
// 使用方式
// $hasBP放在原型上了
// 挂载到Vue原型对象上, 以便组件中直接可见
// Vue.prototype.$hasBP = hasBtnPermission
// 或自定义指令
/*
  <el-button type="danger" v-if="$hasBP('btn.Role.remove')">批量删除</el-button>
* */