You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.9 KiB

  1. import router from './router'
  2. import store from './store'
  3. import { Message } from 'element-ui'
  4. import NProgress from 'nprogress'
  5. import 'nprogress/nprogress.css'
  6. import { getToken } from '@/utils/auth'
  7. import { isPathMatch } from '@/utils/validate'
  8. import { isRelogin } from '@/utils/request'
  9. NProgress.configure({ showSpinner: false })
  10. const whiteList = ['/login', '/loginGld', '/register']
  11. const isWhiteList = (path) => {
  12. return whiteList.some(pattern => isPathMatch(pattern, path))
  13. }
  14. router.beforeEach((to, from, next) => {
  15. NProgress.start()
  16. if (getToken()) {
  17. to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  18. /* has token*/
  19. if (to.path === '/login' || to.path === '/loginGld') {
  20. next({ path: '/index' })
  21. NProgress.done()
  22. }
  23. else if (isWhiteList(to.path)) {
  24. next()
  25. } else {
  26. if (store.getters.roles.length === 0) {
  27. isRelogin.show = true
  28. // 判断当前用户是否已拉取完user_info信息
  29. store.dispatch('GetInfo').then(() => {
  30. isRelogin.show = false
  31. store.dispatch('GenerateRoutes').then(accessRoutes => {
  32. // 根据roles权限生成可访问的路由表
  33. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  34. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  35. })
  36. }).catch(err => {
  37. store.dispatch('LogOut').then(() => {
  38. Message.error(err)
  39. next({path: '/'})
  40. })
  41. })
  42. } else {
  43. next()
  44. }
  45. }
  46. } else {
  47. // 没有token
  48. if (isWhiteList(to.path)) {
  49. // 在免登录白名单,直接进入
  50. next()
  51. } else {
  52. next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
  53. NProgress.done()
  54. }
  55. }
  56. })
  57. router.afterEach(() => {
  58. NProgress.done()
  59. })