菜单权限探索

大多数公司可能多数的做法都是放在前端去控制,后台提供数据。控制路由什么的前端页面写死。这种做法肯定不好或者不合适。正确的做法应该是根据权限动态加载路由

module.exports = [
  {
    id: 1,
    name: 'zhangsan',
    auth: [2,3,6,7]
  },
  {
    id: 2,
    name: 'lisi',
    auth: [2,3,5,6,7,8]
  },
  {
    id: 3,
    name: 'wangwu',
    auth: [2,3,4,5,6,7,8]
  }
]
module.exports = [
  {
    id: 2,
    pid: 0,
    path: '/course',
    name: 'Course',
    title: '课程管理'
  },
  {
    id: 3,
    pid: 2,
    path: 'operate',
    name: 'CourseOperate',
    link: '/course/operate',
    title: '课程操作'
  },
  {
    id: 4,
    pid: 3,
    path: 'info_data',
    name: 'CourseInfoData',
    link: '/course/operate/info_data',
    title: '课程数据'
  },
  {
    id: 5,
    pid: 2,
    path: 'add',
    name: 'CourseAdd',
    link: '/course/add',
    title: '增加课程'
  },
  {
    id: 6,
    pid: 0,
    path: '/student',
    name: 'Student',
    title: '学生管理'
  },
  {
    id: 7,
    pid: 6,
    path: 'operate',
    name: 'StudentOperate',
    link: '/student/operate',
    title: '学生操作'
  },
  {
    id: 8,
    pid: 6,
    path: 'add',
    name: 'SudentAdd',
    link: '/student/add',
    title: '增加学生'
  },
];
const router = require('koa-router')()

const users = require('../data/user');
const routers = require('../data/router');

router.post('/user_router_auth', async (ctx, next) => {
  const { uid } = ctx.request.body;

  if (uid) {
    let authRouterInfo = [];
    
    const userInfo = users.filter(user => user.id == uid)[0];
    userInfo.auth.map((rid) => {
      routers.map((router) => {
        if (router.id === rid) {
          authRouterInfo.push(router);
        }
      })
    })

    ctx.body = authRouterInfo;
  } else {
    next();
  }

  
})

module.exports = router
function formatRouterTree (data) {
  let parents = data.filter(p => p.pid === 0),
      children = data.filter(c => c.pid !== 0);

  dataToTree(parents, children);

  function dataToTree (parents, children) {
    parents.map((p) => {
      children.map((c, i) => {
        if (c.pid === p.id) {
          let _c = JSON.parse(JSON.stringify(children));
          _c.splice(i, 1);
          dataToTree([c], _c);

          if (p.children) {
            p.children.push(c);
          } else {
            p.children = [c];
          }
        }
      })
    })
  }
  
  return parents;
}

function generateRouter (userRouters) {
  let newRouters = userRouters.map((r) => {
    let routes = {
      path: r.path,
      name: r.name,
      component: () => import(`@/views/${r.name}`)
    }

    if (r.children) {
      routes.children = generateRouter(r.children);
    }

    return routes;
  });

  return newRouters;
}

export {
  formatRouterTree,
  generateRouter
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页