permission.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import router from './router'
  2. import type { RouteRecordRaw } from 'vue-router'
  3. import { isRelogin } from '@/config/axios/service'
  4. import { getAccessToken } from '@/utils/auth'
  5. import { useTitle } from '@/hooks/web/useTitle'
  6. import { useNProgress } from '@/hooks/web/useNProgress'
  7. import { usePageLoading } from '@/hooks/web/usePageLoading'
  8. import { useDictStoreWithOut } from '@/store/modules/dict'
  9. import { useUserStoreWithOut } from '@/store/modules/user'
  10. import { usePermissionStoreWithOut } from '@/store/modules/permission'
  11. const { start, done } = useNProgress()
  12. const { loadStart, loadDone } = usePageLoading()
  13. // 路由不重定向白名单
  14. const whiteList = [
  15. '/login',
  16. '/loginAdmin',
  17. '/social-login',
  18. '/auth-redirect',
  19. '/bind',
  20. '/register',
  21. '/oauthLogin/gitee'
  22. ]
  23. // 路由加载前
  24. router.beforeEach(async (to, from, next) => {
  25. start()
  26. loadStart()
  27. if (getAccessToken()) {
  28. if (to.path === '/login') {
  29. next({ path: '/' })
  30. } else {
  31. // 获取所有字典
  32. const dictStore = useDictStoreWithOut()
  33. const userStore = useUserStoreWithOut()
  34. const permissionStore = usePermissionStoreWithOut()
  35. if (!dictStore.getIsSetDict) {
  36. await dictStore.setDictMap()
  37. }
  38. if (!userStore.getIsSetUser) {
  39. isRelogin.show = true
  40. await userStore.setUserInfoAction()
  41. isRelogin.show = false
  42. // 后端过滤菜单
  43. await permissionStore.generateRoutes()
  44. permissionStore.getAddRouters.forEach((route) => {
  45. router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  46. })
  47. const redirectPath = from.query.redirect || to.path
  48. const redirect = decodeURIComponent(redirectPath as string)
  49. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
  50. next(nextData)
  51. } else {
  52. next()
  53. }
  54. }
  55. } else {
  56. // if (to.path.indexOf('loginAdmin') !== -1 && to.query.debugger === '1') {
  57. // next()
  58. // return
  59. // }
  60. if (whiteList.indexOf(to.path) !== -1) {
  61. next()
  62. } else {
  63. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  64. }
  65. }
  66. })
  67. router.afterEach((to) => {
  68. useTitle(to?.meta?.title as string)
  69. done() // 结束Progress
  70. loadDone()
  71. })