index.js
2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
* @Date: 2025-03-20 20:36:36
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-12-04 11:25:22
* @FilePath: /mlaj/src/router/index.js
* @Description: 路由实例创建和导出
*/
import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './routes'
import { checkAuth } from './guards'
import { getUserIsLoginAPI } from '@/api/auth'
import { getUserInfoAPI } from '@/api/users'
const router = createRouter({
history: createWebHashHistory(import.meta.env.VITE_BASE || '/'),
routes,
scrollBehavior() {
// 每次路由切换后,页面滚动到顶部
return { top: 0, left: 0 }
},
})
// 导航守卫
router.beforeEach(async (to, from, next) => {
// 检查用户是否已登录
const currentUser = JSON.parse(localStorage.getItem('currentUser') || 'null')
const redirectRaw = to.query && to.query.redirect
// 登录权限检查(不再自动触发微信授权)
const authResult = checkAuth(to)
if (authResult !== true) {
next(authResult)
return
}
// 登录页统一处理授权回跳与默认重定向
if (to.path === '/login') {
/**
* 情况1:本地已有登录态
* - 有 redirect:跳回来源页
* - 无 redirect:默认跳首页
*/
if (currentUser) {
const redirect = redirectRaw ? decodeURIComponent(redirectRaw) : '/'
next(redirect)
return
}
/**
* 情况2:授权回跳但本地未写入登录态
* - 统一在路由层探测登录
* - 登录为真:写入用户信息,并按 redirect 或首页跳转
*/
try {
const { code, data } = await getUserIsLoginAPI()
if (code && data && data.is_login) {
const { code: uiCode, data: uiData } = await getUserInfoAPI()
if (uiCode) {
const mergedUser = { ...uiData.user, ...uiData.checkin }
localStorage.setItem('currentUser', JSON.stringify(mergedUser))
}
const redirect = redirectRaw ? decodeURIComponent(redirectRaw) : '/'
next(redirect)
return
}
} catch (e) {
// 静默失败,进入登录页
}
}
next()
})
export default router