permission.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. '/social-login',
  17. '/auth-redirect',
  18. '/bind',
  19. '/register',
  20. '/oauthLogin/gitee'
  21. ]
  22. // 路由加载前
  23. router.beforeEach(async (to, from, next) => {
  24. start()
  25. loadStart()
  26. if (getAccessToken()) {
  27. if (to.path === '/login') {
  28. next({ path: '/' })
  29. } else {
  30. // 获取所有字典
  31. const dictStore = useDictStoreWithOut()
  32. const userStore = useUserStoreWithOut()
  33. const permissionStore = usePermissionStoreWithOut()
  34. if (!dictStore.getIsSetDict) {
  35. await dictStore.setDictMap()
  36. }
  37. if (!userStore.getIsSetUser) {
  38. isRelogin.show = true
  39. await userStore.setUserInfoAction()
  40. isRelogin.show = false
  41. // 后端过滤菜单
  42. await permissionStore.generateRoutes()
  43. permissionStore.getAddRouters.forEach((route) => {
  44. router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  45. })
  46. const redirectPath = from.query.redirect || to.path
  47. const redirect = decodeURIComponent(redirectPath as string)
  48. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
  49. next(nextData)
  50. } else {
  51. next()
  52. }
  53. }
  54. } else {
  55. if (whiteList.indexOf(to.path) !== -1) {
  56. next()
  57. } else {
  58. next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
  59. }
  60. }
  61. })
  62. router.afterEach((to) => {
  63. useTitle(to?.meta?.title as string)
  64. done() // 结束Progress
  65. loadDone()
  66. })