permission.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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.path){
  34. // 防止空路由出现的警告,设置默认path
  35. route.path = '/path';
  36. }
  37. if (route.component) {
  38. // Layout组件特殊处理
  39. if (route.component === 'Layout') {
  40. route.component = Layout
  41. } else {
  42. route.component = loadView(route.component)
  43. }
  44. }
  45. if (route.children != null && route.children && route.children.length) {
  46. route.children = filterAsyncRouter(route.children)
  47. }
  48. return true
  49. })
  50. }
  51. export const loadView = (view) => { // 路由懒加载
  52. return (resolve) => require([`@/views/${view}`], resolve)
  53. }
  54. export default permission