fix: 修改路由功能

This commit is contained in:
2026-06-17 12:23:23 +08:00
parent dedf172539
commit 18ff5cacfe
2 changed files with 26 additions and 46 deletions

View File

@@ -22,18 +22,34 @@ function setupCommonGuard(router: Router) {
router.beforeEach(async (to) => { router.beforeEach(async (to) => {
const accountStore = useAccountStore() const accountStore = useAccountStore()
// 首次导航时验证 token 有效性(检查持久化的 token 是否过期)
// await accountStore.initAuth()
// 已登录用户访问公开路由(如登录页),直接跳转首页 // 已登录用户访问公开路由(如登录页),直接跳转首页
if (accountStore.isLoggedIn() && isPublicPath(to.path)) { if (!!accountStore.accessToken && isPublicPath(to.path)) {
return '/' return '/'
} }
// accessToken 检查
if (!accountStore.accessToken) {
// 明确声明忽略权限访问权限,则可以访问
if (to.meta.ignoreAccess) {
return true
}
// 未登录用户访问非公开路由,跳转登录页 // 未登录用户访问非公开路由,跳转登录页
if (!accountStore.isLoggedIn() && !isPublicPath(to.path)) { if (!isPublicPath(to.path)) {
// 将原本要访问的路径作为 redirect 参数传递,登录后可跳回 // 将原本要访问的路径作为 redirect 参数传递,登录后可跳回
return { path: '/auth/login', query: { redirect: to.fullPath } } return { path: '/auth/login', query: { redirect: to.fullPath }, replace: true }
}
// 没有访问权限,跳转登录页面
if (to.fullPath !== '/auth/login') {
return {
path: '/auth/login',
query: { redirect: to.fullPath },
// 携带当前跳转的页面,登录后重新跳转该页面
replace: true
}
}
return to
} }
return true return true

View File

@@ -39,42 +39,6 @@ export const useAccountStore = defineStore(
/** 是否已完成初始验证(防止重复请求) */ /** 是否已完成初始验证(防止重复请求) */
const isInitialized = ref(false) const isInitialized = ref(false)
/**
* 判断当前是否已登录
* token 存在且已验证有效才算已登录
*/
const isLoggedIn = () => isTokenValid.value
/**
* 初始化认证状态
*
* 用持久化的 Access Token 向服务端验证是否仍然有效。
* 只会在首次调用时真正发请求,后续调用直接跳过。
*
* - 无 token → 无操作
* - token 有效 → 拉取用户信息,标记已登录
* - token 过期 → requestClient 拦截器自动调用 refreshAccessToken() 刷新后重试,
* 若刷新也失败则抛出异常,此处 catch 后清除认证状态
*/
const initAuth = async () => {
console.log('initAuth', isInitialized.value)
// 已验证过,跳过
if (isInitialized.value) return
isInitialized.value = true
// 没有持久化的 Access Token
if (!accessToken.value) return
try {
await fetchUserInfo()
// 成功获取用户信息token 有效
isTokenValid.value = true
} catch {
// 请求失败(包括自动刷新也失败),清除认证状态
clearAuth()
}
}
/** /**
* 用户登录 * 用户登录
* 调用登录 API成功后存储双 Token 并获取用户信息 * 调用登录 API成功后存储双 Token 并获取用户信息
@@ -150,12 +114,12 @@ export const useAccountStore = defineStore(
isInitialized.value = false isInitialized.value = false
} }
console.log('useAccountStore', accessToken.value)
return { return {
accountInfo, accountInfo,
accessToken, accessToken,
refreshToken, refreshToken,
isLoggedIn,
initAuth,
login, login,
register, register,
logout, logout,