index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import { loginRouter } from './routes.js'
  4. import store from '@/store/index'
  5. import { Message } from 'element-ui'
  6. Vue.use(Router)
  7. const originalPush = Router.prototype.push
  8. const router = new Router({
  9. routes: [loginRouter]
  10. })
  11. Router.prototype.push = function push(location) {
  12. return originalPush.call(this, location).catch(err => err)
  13. }
  14. const LOGIN_PAGE_NAME = 'login'
  15. // 跳转之前
  16. router.beforeEach(async (to, from, next) => {
  17. const token = localStorage.getItem('Token')
  18. if (!token && to.name !== LOGIN_PAGE_NAME) {
  19. // 未登录且要跳转的页面不是登录页
  20. next({
  21. name: LOGIN_PAGE_NAME // 跳转到登录页
  22. })
  23. } else if (to.name === LOGIN_PAGE_NAME) {
  24. next()
  25. } else {
  26. if (token) {
  27. if (!store.state.permission.permissionList) {
  28. try {
  29. let accessRoutes = await store.dispatch('permission/FETCH_PERMISSION')
  30. await router.addRoutes(accessRoutes)
  31. let flag = ruleValidate(accessRoutes, to.path)
  32. if (flag) {
  33. next({ ...to, replace: true })
  34. }
  35. } catch (err) {
  36. if (err.code != '0') {
  37. next({
  38. name: LOGIN_PAGE_NAME // 跳转到登录页
  39. })
  40. }
  41. }
  42. } else {
  43. // store.dispatch('permission/FETCH_AUTHORID')
  44. next()
  45. }
  46. } else {
  47. next({
  48. name: LOGIN_PAGE_NAME
  49. })
  50. }
  51. }
  52. })
  53. function ruleValidate(data, path) {
  54. let flag = false
  55. function judgeChildren(data, path) {
  56. data.forEach(e => {
  57. if (flag) {
  58. return
  59. }
  60. if (e.path === path) {
  61. flag = true
  62. return
  63. } else if (e.children && e.children.length) {
  64. judgeChildren(e.children, path)
  65. }
  66. })
  67. }
  68. judgeChildren(data, path)
  69. return flag
  70. }
  71. export default router