permission.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { useUserStore } from '@/pinia/modules/user'
  2. import { useRouterStore } from '@/pinia/modules/router'
  3. import getPageTitle from '@/utils/page'
  4. import router from '@/router'
  5. let asyncRouterFlag = 0
  6. const whiteList = ['Login', 'Init']
  7. const getRouter = async(userStore) => {
  8. const routerStore = useRouterStore()
  9. await routerStore.SetAsyncRouter()
  10. await userStore.GetUserInfo()
  11. const asyncRouters = routerStore.asyncRouters
  12. asyncRouters.forEach(asyncRouter => {
  13. router.addRoute(asyncRouter)
  14. })
  15. }
  16. async function handleKeepAlive(to) {
  17. if (to.matched.some(item => item.meta.keepAlive)) {
  18. if (to.matched && to.matched.length > 2) {
  19. for (let i = 1; i < to.matched.length; i++) {
  20. const element = to.matched[i - 1]
  21. if (element.name === 'layout') {
  22. to.matched.splice(i, 1)
  23. await handleKeepAlive(to)
  24. }
  25. // 如果没有按需加载完成则等待加载
  26. if (typeof element.components.default === 'function') {
  27. await element.components.default()
  28. await handleKeepAlive(to)
  29. }
  30. }
  31. }
  32. }
  33. }
  34. router.beforeEach(async(to, from, next) => {
  35. const userStore = useUserStore()
  36. to.meta.matched = [...to.matched]
  37. handleKeepAlive(to)
  38. const token = userStore.token
  39. // 在白名单中的判断情况
  40. document.title = getPageTitle(to.meta.title, to)
  41. if (whiteList.indexOf(to.name) > -1) {
  42. if (token) {
  43. if (!asyncRouterFlag && whiteList.indexOf(from.name) < 0) {
  44. asyncRouterFlag++
  45. await getRouter(userStore)
  46. }
  47. next({ name: userStore.userInfo.authority.defaultRouter })
  48. } else {
  49. next()
  50. }
  51. } else {
  52. // 不在白名单中并且已经登陆的时候
  53. if (token) {
  54. // 添加flag防止多次获取动态路由和栈溢出
  55. if (!asyncRouterFlag && whiteList.indexOf(from.name) < 0) {
  56. asyncRouterFlag++
  57. await getRouter(userStore)
  58. if (userStore.token) {
  59. next({ ...to, replace: true })
  60. } else {
  61. next({
  62. name: 'Login',
  63. query: { redirect: to.href }
  64. })
  65. }
  66. } else {
  67. if (to.matched.length) {
  68. next()
  69. } else {
  70. next({ path: '/layout/404' })
  71. }
  72. }
  73. }
  74. // 不在白名单中并且未登陆的时候
  75. if (!token) {
  76. next({
  77. name: 'Login',
  78. query: {
  79. redirect: document.location.hash
  80. }
  81. })
  82. }
  83. }
  84. })