index.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // src/router/index.ts
  2. import { createRouter, createWebHistory } from 'vue-router'
  3. import { routes } from './routes'
  4. import { useUserStoreWithOut } from '@/stores/modules/user'
  5. // 创建 Router 实例
  6. const router = createRouter({
  7. history: createWebHistory(import.meta.env.BASE_URL),
  8. routes,
  9. })
  10. // 路由守卫
  11. router.beforeEach((to, from, next) => {
  12. const userStore = useUserStoreWithOut()
  13. if (to.name === 'Login' || to.meta.requiresAuth) {
  14. if (typeof to.query.pushRecordId === 'string') {
  15. userStore.setPushRecordId(to.query.pushRecordId)
  16. }
  17. if (to.name === 'Login' && to.query.from === 'reject') userStore.LogOut()
  18. }
  19. const token = userStore.hasValidSession()
  20. const pushRecordId = userStore.pushRecordId
  21. if (to.meta.requiresAuth && (!token || !pushRecordId)) {
  22. // 未登录时跳转登录页
  23. next({
  24. path: '/login',
  25. query: pushRecordId ? { pushRecordId } : {},
  26. })
  27. } else {
  28. next()
  29. }
  30. if (to.meta && to.meta.title) {
  31. document.title = to.meta.title as string
  32. } else {
  33. // 可设置默认标题
  34. document.title = '默认标题'
  35. }
  36. })
  37. // 可选:设置页面标题
  38. router.afterEach((to) => {
  39. if (to.meta.title) {
  40. document.title = to.meta.title as string
  41. }
  42. })
  43. export default router