permission.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { constantRoutes, asyncRoutes, afterRoutes } from '@/router'
  2. /**
  3. * 返回当前路由名称对应的菜单
  4. * @param menus 菜单列表
  5. * @param name 路由名称
  6. */
  7. function filterMeun(menus, name) {
  8. if (name) {
  9. for (let i = 0; i < menus.length; i++) {
  10. const menu = menus[i]
  11. if (name === menu.name) {
  12. return menu
  13. }
  14. }
  15. }
  16. return null
  17. }
  18. /**
  19. * 通过后台请求的菜单列表递归过滤路由表
  20. * @param routes asyncRoutes
  21. * @param menus 接口返回的菜单
  22. */
  23. export function filterAsyncRoutes(routes, menus) {
  24. const res = []
  25. routes.forEach(route => {
  26. const tmp = { ...route }
  27. const meun = filterMeun(menus, tmp.name)
  28. if (meun != null && meun.title) {
  29. tmp.hidden = meun.hidden !== 0
  30. // 显示的菜单替换后台设置的标题
  31. if (!tmp.hidden) {
  32. tmp.meta.title = meun.title
  33. tmp.sort = meun.sort
  34. }
  35. if (meun.icon) {
  36. tmp.meta.icon = meun.icon
  37. }
  38. if (tmp.children) {
  39. tmp.children = filterAsyncRoutes(tmp.children, menus)
  40. }
  41. res.push(tmp)
  42. }
  43. })
  44. return res
  45. }
  46. /**
  47. * 对菜单进行排序
  48. */
  49. function sortRouters(accessedRouters) {
  50. for (let i = 0; i < accessedRouters.length; i++) {
  51. const router = accessedRouters[i]
  52. if (router.children && router.children.length > 0) {
  53. router.children.sort(compare('sort'))
  54. }
  55. }
  56. accessedRouters.sort(compare('sort'))
  57. }
  58. /**
  59. * 升序比较函数
  60. */
  61. function compare(p) {
  62. return (m, n) => {
  63. const a = m[p]
  64. const b = n[p]
  65. return a - b
  66. }
  67. }
  68. const state = {
  69. routes: [],
  70. addRoutes: []
  71. }
  72. const mutations = {
  73. SET_ROUTES: (state, routes) => {
  74. state.addRoutes = routes
  75. state.routes = constantRoutes.concat(routes)
  76. }
  77. }
  78. const actions = {
  79. generateRoutes({ commit }, menus) {
  80. return new Promise(resolve => {
  81. // 通过后台请求的菜单列表递归过滤路由表
  82. const roleAsyncRoutes = filterAsyncRoutes(asyncRoutes, menus)
  83. // 对可访问菜单进行排序
  84. sortRouters(roleAsyncRoutes)
  85. // 拼接尾部公共菜单
  86. const accessedRoutes = roleAsyncRoutes.concat(afterRoutes)
  87. commit('SET_ROUTES', accessedRoutes)
  88. resolve(accessedRoutes)
  89. })
  90. }
  91. }
  92. export default {
  93. namespaced: true,
  94. state,
  95. mutations,
  96. actions
  97. }