pemission.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import router from './router'
  2. import store from './store'
  3. import { getItem } from '@/utils/index'
  4. import { TOKEN } from '@/utils/constant'
  5. import { filterPermissionsRoutes, flattenedRoutes, buildTreeData } from '@/router/private-routes'
  6. import Layout from '@/layout/index.vue'
  7. // 白名单
  8. const whiteList = ['/login']
  9. /**
  10. * @param {*} to 到哪去
  11. * @param {*} from 从哪来
  12. * @param {*} next 是否要去
  13. */
  14. router.beforeEach(async (to, from, next) => {
  15. if (getItem(TOKEN)) {
  16. if (to.path === '/login') {
  17. next('/')
  18. } else {
  19. if (!store.getters.hasUserInfo) {
  20. const { permissions } = await store.dispatch('user/getUserInfo')
  21. const fRoutes = await filterPermissionsRoutes(flattenedRoutes, permissions)
  22. fRoutes.forEach(async (item) => {
  23. await router.addRoute(item)
  24. })
  25. const navMenus = fRoutes.map(({ name, meta, path }) => ({ name, meta, path, children: [] }))
  26. store.dispatch('permission/setNavMenus', buildTreeData(navMenus))
  27. await router.addRoute({
  28. path: '/*',
  29. name: 'Layout',
  30. component: Layout,
  31. children: [
  32. {
  33. path: '/*',
  34. name: 'redirect',
  35. component: () => import('@/views/err-page/404.vue')
  36. }
  37. ]
  38. })
  39. return next(to.path)
  40. next({ ...to, replace: true })
  41. }
  42. next()
  43. }
  44. } else {
  45. // 2. 用户未登录,只允许进入白名单
  46. if (whiteList.indexOf(to.path) > -1) {
  47. next()
  48. } else {
  49. next('/login')
  50. }
  51. }
  52. })