permission.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 { isRelogin } from '@/utils/request'
  8. NProgress.configure({ showSpinner: false })
  9. const whiteList = ['/login', '/register']
  10. router.beforeEach((to, from, next) => {
  11. NProgress.start()
  12. if (getToken()) {
  13. to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
  14. /* has token*/
  15. if (to.path === '/login') {
  16. next({ path: '/' })
  17. NProgress.done()
  18. } else {
  19. if (store.getters.roles.length === 0) {
  20. isRelogin.show = true
  21. // 判断当前用户是否已拉取完user_info信息
  22. store.dispatch('GetInfo').then(() => {
  23. isRelogin.show = false
  24. store.dispatch('GenerateRoutes').then(accessRoutes => {
  25. // 根据roles权限生成可访问的路由表
  26. router.addRoutes(accessRoutes) // 动态添加可访问路由表
  27. // console.log(accessRoutes, to, 'accessRoutes11');
  28. if(accessRoutes[0].children[0].path != 'index' && (to.path === '/index' || to.path === '/')) {
  29. next({ ...accessRoutes[0].children[0], replace: true }) // hack方法 确保addRoutes已完成
  30. } else if(accessRoutes[0].children[0].path == 'index' && (to.path === '/index' || to.path === '/')){
  31. next({ ...accessRoutes[0].children[0], replace: true })
  32. } else {
  33. next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
  34. }
  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 (whiteList.indexOf(to.path) !== -1) {
  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. })