permission.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { constantRoutes } from '@/router'
  2. import { getRouters } from '@/api/menu'
  3. import Layout from '@/layout/index'
  4. import ParentView from '@/components/ParentView';
  5. const permission = {
  6. state: {
  7. routes: [],
  8. addRoutes: [],
  9. sidebarRouters: []
  10. },
  11. mutations: {
  12. SET_ROUTES: (state, routes) => {
  13. state.addRoutes = routes
  14. state.routes = constantRoutes.concat(routes)
  15. },
  16. SET_SIDEBAR_ROUTERS: (state, routers) => {
  17. state.sidebarRouters = routers
  18. },
  19. },
  20. actions: {
  21. // 生成路由
  22. GenerateRoutes({ commit }) {
  23. return new Promise(resolve => {
  24. // 向后端请求路由数据
  25. getRouters().then(res => {
  26. const sdata = JSON.parse(JSON.stringify(res.data))
  27. const rdata = JSON.parse(JSON.stringify(res.data))
  28. const sidebarRoutes = filterAsyncRouter(sdata)
  29. const rewriteRoutes = filterAsyncRouter(rdata, true)
  30. rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
  31. commit('SET_ROUTES', rewriteRoutes)
  32. commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
  33. resolve(rewriteRoutes)
  34. })
  35. })
  36. }
  37. }
  38. }
  39. // 遍历后台传来的路由字符串,转换为组件对象
  40. function filterAsyncRouter(asyncRouterMap, isRewrite = false) {
  41. return asyncRouterMap.filter(route => {
  42. if (isRewrite && route.children) {
  43. route.children = filterChildren(route.children)
  44. }
  45. if (route.component) {
  46. // Layout ParentView 组件特殊处理
  47. if (route.component === 'Layout') {
  48. route.component = Layout
  49. } else if (route.component === 'ParentView') {
  50. route.component = ParentView
  51. } else {
  52. route.component = loadView(route.component)
  53. }
  54. }
  55. if (route.children != null && route.children && route.children.length) {
  56. route.children = filterAsyncRouter(route.children, route, isRewrite)
  57. }
  58. return true
  59. })
  60. }
  61. function filterChildren(childrenMap) {
  62. var children = []
  63. childrenMap.forEach((el, index) => {
  64. if (el.children && el.children.length) {
  65. if (el.component === 'ParentView') {
  66. el.children.forEach(c => {
  67. c.path = el.path + '/' + c.path
  68. if (c.children && c.children.length) {
  69. children = children.concat(filterChildren(c.children, c))
  70. return
  71. }
  72. children.push(c)
  73. })
  74. childrenMap.splice(index, 1)
  75. return
  76. }
  77. }
  78. children = children.concat(el)
  79. })
  80. return children
  81. }
  82. export const loadView = (view) => { // 路由懒加载
  83. return (resolve) => require([`@/views/${view}`], resolve)
  84. }
  85. export default permission