permission.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import router from './router'
  2. import { useAppStoreWithOut } from '@/store/modules/app'
  3. import { useCache } from '@/hooks/web/useCache'
  4. import type { RouteRecordRaw } from 'vue-router'
  5. import { useTitle } from '@/hooks/web/useTitle'
  6. import { useNProgress } from '@/hooks/web/useNProgress'
  7. import { usePermissionStoreWithOut } from '@/store/modules/permission'
  8. import { usePageLoading } from '@/hooks/web/usePageLoading'
  9. const permissionStore = usePermissionStoreWithOut()
  10. const appStore = useAppStoreWithOut()
  11. const { wsCache } = useCache()
  12. const { start, done } = useNProgress()
  13. const { loadStart, loadDone } = usePageLoading()
  14. const whiteList = ['/login'] // 不重定向白名单
  15. router.beforeEach(async (to, from, next) => {
  16. start()
  17. loadStart()
  18. if (wsCache.get(appStore.getUserInfo)) {
  19. if (to.path === '/login') {
  20. next({ path: '/' })
  21. } else {
  22. if (permissionStore.getIsAddRouters) {
  23. next()
  24. return
  25. }
  26. await permissionStore.generateRoutes()
  27. permissionStore.getAddRouters.forEach((route) => {
  28. router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  29. })
  30. const redirectPath = from.query.redirect || to.path
  31. const redirect = decodeURIComponent(redirectPath as string)
  32. const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
  33. permissionStore.setIsAddRouters(true)
  34. next(to.path === '/' ? { path: permissionStore.addRouters[0]?.path as string } : nextData)
  35. }
  36. } else {
  37. if (whiteList.indexOf(to.path) !== -1) {
  38. next()
  39. } else {
  40. next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
  41. }
  42. }
  43. })
  44. router.afterEach((to) => {
  45. useTitle(to?.meta?.title as string)
  46. done() // 结束Progress
  47. loadDone()
  48. })