permission.ts 1.6 KB

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