index.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { createRouter, createWebHistory } from 'vue-router'
  2. import NProgress from '@/config/progress'
  3. import index from './modules'
  4. import { useAuthStore } from '@/stores/modules/auth'
  5. import { useCachedViewStore } from '@/stores/modules/cachedView'
  6. import { getQueryString } from '@/utils'
  7. const router = createRouter({
  8. history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  9. scrollBehavior: () => ({ left: 0, top: 0 }),
  10. routes: index
  11. })
  12. // 白名单地址
  13. const whileList = ['/401', '/403', '/404', '/500', '/preview']
  14. router.beforeEach(async (to, from, next) => {
  15. const authStore = useAuthStore()
  16. const cachedViewStore = useCachedViewStore()
  17. // 添加缓存
  18. cachedViewStore.addCached(to)
  19. // 进度条开始
  20. NProgress.start()
  21. // 动态设置标题
  22. const title = import.meta.env.VITE_GLOB_APP_TITLE
  23. document.title = to.meta.title ? `${to.meta.title} - ${title}` : title
  24. const token = getQueryString(window.location.href,"token")
  25. if(token){
  26. next()
  27. }else{
  28. // 是否为跳转登录页
  29. if (to.path.toLocaleLowerCase() === '/login') {
  30. if (authStore.tokenGet) {
  31. // 哪来回哪去
  32. return next(from.fullPath)
  33. }
  34. return next()
  35. }
  36. // 白名单中的路由直接放行
  37. if (whileList.includes(to.path)) {
  38. return next()
  39. }
  40. // 不携带token的情况下,跳转到登录页
  41. if (!authStore.tokenGet) {
  42. next({ path: `/login?redirect=${to.fullPath}`, replace: true })
  43. return
  44. }
  45. // 获取用户信息
  46. if (!authStore.usernameGet) {
  47. await authStore.getInfo()
  48. }
  49. next()
  50. }
  51. })
  52. router.afterEach(() => {
  53. NProgress.done()
  54. })
  55. router.onError(() => {
  56. NProgress.done()
  57. })
  58. export default router