permission.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import router from './router'
  2. import { store } from '@/store/index'
  3. import getPageTitle from '@/utils/page'
  4. let asyncRouterFlag = 0
  5. const whiteList = ['Login', 'Init']
  6. router.beforeEach(async(to, from, next) => {
  7. const token = store.getters['user/token']
  8. // 在白名单中的判断情况
  9. document.title = getPageTitle(to.meta.title)
  10. if (whiteList.indexOf(to.name) > -1) {
  11. if (token) {
  12. next({ path: '/layout/dashboard' })
  13. } else {
  14. next()
  15. }
  16. } else {
  17. // 不在白名单中并且已经登陆的时候
  18. if (token) {
  19. // 添加flag防止多次获取动态路由和栈溢出
  20. if (!asyncRouterFlag) {
  21. asyncRouterFlag++
  22. await store.dispatch('router/SetAsyncRouter')
  23. await store.dispatch('user/GetUserInfo')
  24. const asyncRouters = store.getters['router/asyncRouters']
  25. asyncRouters.map(asyncRouter => {
  26. router.addRoute(asyncRouter)
  27. })
  28. next({ ...to, replace: true })
  29. } else {
  30. next()
  31. }
  32. }
  33. // 不在白名单中并且未登陆的时候
  34. if (!token) {
  35. next({
  36. name: 'Login',
  37. query: {
  38. redirect: document.location.hash
  39. }
  40. })
  41. }
  42. }
  43. })