permission.js 1.2 KB

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