index.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import {createRouter, createWebHistory} from 'vue-router'
  2. import staticRouter from './modules/static'
  3. import webRouter from './modules/web'
  4. import manageRouter from './modules/manage'
  5. import Temp404 from '@/views/global/temp/404.vue'
  6. import {ElLoading, ElMessage} from "element-plus";
  7. import {useAppStore, useThemeStore} from "@/stores";
  8. import {toLogin} from "@/utils/permissions";
  9. import {getCurrentUser} from "@/api/modules/manage/user";
  10. import {sysThemeGetThemeByThemeType} from "@/api/modules/manage/theme";
  11. const routes = [
  12. ...staticRouter,
  13. { path: '/:pathMatch(.*)*', name: 'NotFound', component: Temp404 },
  14. { path: '', redirect: '/web' },
  15. webRouter,
  16. ]
  17. const router = createRouter({
  18. history: createWebHistory(),
  19. routes,
  20. });
  21. router.beforeEach((to, from , next) => {
  22. const AppStore = useAppStore()
  23. const ThemeStore = useThemeStore()
  24. if (themeConfig && !ThemeStore.init) {
  25. ThemeStore.setTheme(themeConfig)
  26. }
  27. if (userInfo) {
  28. if (!AppStore.userInfo) {
  29. AppStore.$patch((state) => {
  30. state.userInfo = userInfo
  31. })
  32. }
  33. if (to.query.routeTitle) {
  34. to.meta.title = to.query.routeTitle
  35. }
  36. document.title = to.meta?.title || ThemeStore.title || import.meta.env.VITE_TITLE
  37. next()
  38. } else if (to.path === '/login') {
  39. next()
  40. } else {
  41. ElMessage.error('用户信息获取失败!')
  42. toLogin()
  43. }
  44. })
  45. let userInfo = null
  46. let themeConfig = null
  47. export const initMainRouter = async () => {
  48. if (localStorage.getItem('ss_token')) {
  49. const loading = ElLoading.service({
  50. lock: true,
  51. text: '加载中……',
  52. background: 'rgba(0, 0, 0, 0.7)',
  53. })
  54. await Promise.all([
  55. getCurrentUser(),
  56. sysThemeGetThemeByThemeType(),
  57. ]).then(async ([user, theme]) => {
  58. userInfo = user.data
  59. userInfo.isAdmin = true
  60. if (userInfo?.isAdmin) {
  61. router.addRoute(manageRouter)
  62. }
  63. themeConfig = theme.data.themeStyle ? JSON.parse(theme.data.themeStyle) : {}
  64. loading.close()
  65. })
  66. } else if (location.pathname !== '/login') {
  67. toLogin()
  68. }
  69. }
  70. export default router;