feat: add authentication initialization logic and loading state to App component

This commit is contained in:
ethan.chen
2025-05-26 18:28:03 +08:00
parent 6d07c482db
commit 30908806e4

View File

@@ -21,6 +21,7 @@
// 状态管理
let isAuthenticated = $state(false);
let isInitializing = $state(true); // 新增:初始化状态
let username = $state('');
let password = $state('');
let error = $state('');
@@ -45,6 +46,42 @@
{ id: 'other', label: '其他' }
];
// 初始化函数:检查认证状态
async function initializeAuth() {
const auth = localStorage.getItem('auth');
if (auth) {
try {
// 使用 page 接口验证登录状态
const response = await request.get<ApiResponse<PageResponse>>('/media/page', {
params: {
type: 'game',
currentPage: 1,
pageSize: 10
}
});
if (response.data.code === 0) {
isAuthenticated = true;
error = '';
// 设置初始数据
mediaList = response.data.data.list;
totalItems = response.data.data.total;
} else {
// 如果认证失败,清除存储的认证信息
localStorage.removeItem('auth');
}
} catch (e: any) {
// 如果请求失败,清除存储的认证信息
localStorage.removeItem('auth');
error = e.message || 'Connection error';
}
}
isInitializing = false; // 初始化完成
}
// 页面加载时初始化认证状态
initializeAuth();
// 获取媒体列表
async function fetchMediaList() {
loading = true;
@@ -138,7 +175,14 @@
<title>My Score</title>
</svelte:head>
{#if !isAuthenticated}
{#if isInitializing}
<div class="min-h-screen flex items-center justify-center bg-gray-100">
<div class="text-center">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600 mx-auto"></div>
<p class="mt-4 text-gray-600">加载中...</p>
</div>
</div>
{:else if !isAuthenticated}
<div class="min-h-screen flex items-center justify-center bg-gray-100" transition:fade>
<div class="w-[480px] space-y-8 p-8 bg-white rounded-lg shadow-lg">
<div>