permission.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { constantRoutes } from '@/router'
  2. import { getRouters } from '@/api/menu'
  3. import Layout from '@/layout/index'
  4. const permission = {
  5. state: {
  6. routes: [],
  7. addRoutes: []
  8. },
  9. mutations: {
  10. SET_ROUTES: (state, routes) => {
  11. state.addRoutes = routes
  12. state.routes = constantRoutes.concat(routes)
  13. }
  14. },
  15. actions: {
  16. // 生成路由
  17. GenerateRoutes({ commit }) {
  18. return new Promise(resolve => {
  19. // 向后端请求路由数据
  20. getRouters().then(res => {
  21. const accessedRoutes = filterAsyncRouter(res.data)
  22. accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
  23. commit('SET_ROUTES', accessedRoutes)
  24. resolve(accessedRoutes)
  25. })
  26. })
  27. }
  28. }
  29. }
  30. // 遍历后台传来的路由字符串,转换为组件对象
  31. function filterAsyncRouter(asyncRouterMap) {
  32. return asyncRouterMap.filter(route => {
  33. if (route.component) {
  34. // Layout组件特殊处理
  35. if (route.component === 'Layout') {
  36. route.component = Layout
  37. } else {
  38. route.component = loadView(route.component)
  39. }
  40. }
  41. if (route.children != null && route.children && route.children.length) {
  42. route.children = filterAsyncRouter(route.children)
  43. }
  44. return true
  45. })
  46. }
  47. export const loadView = (view) => { // 路由懒加载
  48. return (resolve) => require([`@/views/${view}`], resolve)
  49. }
  50. export default permission