permission.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import Vue from 'vue'
  2. import router from './router'
  3. import store from './store'
  4. import NProgress from 'nprogress' // progress bar
  5. import '@/components/NProgress/nprogress.less' // progress bar custom style
  6. import notification from 'ant-design-vue/es/notification'
  7. import { setDocumentTitle, domTitle } from '@/utils/domUtil'
  8. import { ACCESS_TOKEN } from '@/store/mutation-types'
  9. import BaseTool from '@/utils/tool'
  10. import { GlobalConstant } from '@/constant'
  11. NProgress.configure({ showSpinner: false }) // NProgress Configuration
  12. const whiteList = ['login', 'register', 'registerResult', GlobalConstant.SINGLE_LOGIN_ROUTER_NAME] // no redirect whitelist
  13. router.beforeEach((to, from, next) => {
  14. if (to.path === GlobalConstant.PC_INDEX_PATH) {
  15. if (BaseTool.Util._isMobile()) {
  16. next({ path: GlobalConstant.MOBILE_INDEX_PATH, query: { } })
  17. NProgress.done()
  18. return
  19. }
  20. }
  21. // 单点登录
  22. if (to.name === GlobalConstant.SINGLE_LOGIN_ROUTER_NAME) {
  23. next()
  24. return
  25. }
  26. NProgress.start() // start progress bar
  27. to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  28. if (Vue.ls.get(ACCESS_TOKEN)) {
  29. /* has token */
  30. if (to.path === '/user/login') {
  31. next({ path: GlobalConstant.PC_INDEX_PATH })
  32. NProgress.done()
  33. } else {
  34. if (store.getters.roles.length === 0) {
  35. store
  36. .dispatch('GetInfo')
  37. .then(res => {
  38. const menus = res.data.menuTrees
  39. store.dispatch('GenerateRoutes', { menus }).then(() => {
  40. // 根据roles权限生成可访问的路由表
  41. // 动态添加可访问路由表
  42. router.addRoutes(store.getters.addRouters)
  43. const redirect = decodeURIComponent(from.query.redirect || to.path)
  44. if (to.path === redirect) {
  45. // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
  46. next({ ...to, replace: true })
  47. } else {
  48. // 跳转到目的路由
  49. next({ path: redirect })
  50. }
  51. })
  52. })
  53. .catch(() => {
  54. notification.error({
  55. message: '错误',
  56. description: '请求用户信息失败,请重试'
  57. })
  58. store.dispatch('Logout').then(() => {
  59. next({ path: '/user/login', query: { redirect: to.fullPath } })
  60. })
  61. })
  62. } else {
  63. next()
  64. }
  65. }
  66. } else {
  67. if (whiteList.includes(to.name)) {
  68. // 在免登录白名单,直接进入
  69. next()
  70. } else {
  71. // next({ path: '/user/login', query: { redirect: to.fullPath } })
  72. next({ path: '/user/login', query: { } })
  73. NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  74. }
  75. }
  76. })
  77. router.afterEach(() => {
  78. NProgress.done() // finish progress bar
  79. })