[로딩 시스템 추가] 전역 로딩 오버레이 및 상태 관리 스토어 구현, 로딩 카운터 방식으로 비동기 작업 관리 기능 추가

This commit is contained in:
2025-09-24 10:53:08 +09:00
parent 1229faa777
commit b866242d43
7 changed files with 571 additions and 13 deletions

View File

@@ -2,6 +2,9 @@
<NuxtLayout>
<NuxtPage :keepalive="true" />
</NuxtLayout>
<!-- 전역 로딩 오버레이 -->
<GlobalLoading :show-details="true" />
</template>
<!-- <script setup lang="ts">

View File

@@ -0,0 +1,220 @@
<template>
<Teleport to="body">
<Transition
name="loading-fade"
enter-active-class="transition-opacity duration-300"
leave-active-class="transition-opacity duration-300"
enter-from-class="opacity-0"
enter-to-class="opacity-100"
leave-from-class="opacity-100"
leave-to-class="opacity-0"
>
<div
v-if="isLoading"
class="global-loading-overlay"
@click.self="handleOverlayClick"
>
<div class="loading-container">
<!-- 스피너 -->
<div class="loading-spinner">
<div class="spinner"></div>
</div>
<!-- 로딩 메시지 -->
<div class="loading-message">
<p class="message-text">{{ currentMessage }}</p>
<p v-if="loadingCount > 1" class="count-text">
({{ loadingCount }} 작업 진행 )
</p>
</div>
<!-- 진행 중인 작업 목록 (개발 모드에서만) -->
<div
v-if="showDetails && loadingMessages.length > 1"
class="loading-details"
>
<details class="details">
<summary class="details-summary">진행 중인 작업 보기</summary>
<ul class="details-list">
<li
v-for="(message, index) in loadingMessages"
:key="index"
class="details-item"
>
{{ message }}
</li>
</ul>
</details>
</div>
</div>
</div>
</Transition>
</Teleport>
</template>
<script setup lang="ts">
interface Props {
/** 오버레이 클릭 시 로딩 취소 허용 여부 */
allowCancel?: boolean;
/** 개발 모드에서 상세 정보 표시 여부 */
showDetails?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
allowCancel: false,
showDetails: false,
});
const { isLoading, currentMessage, loadingCount, loadingMessages, clearAll } =
useLoading();
// 오버레이 클릭 처리
const handleOverlayClick = () => {
if (props.allowCancel) {
clearAll();
}
};
</script>
<style scoped>
.global-loading-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
backdrop-filter: blur(2px);
}
.loading-container {
background: white;
border-radius: 12px;
padding: 2rem;
box-shadow:
0 20px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04);
text-align: center;
min-width: 200px;
max-width: 400px;
}
.loading-spinner {
margin-bottom: 1rem;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f4f6;
border-top: 4px solid #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.loading-message {
margin-bottom: 1rem;
}
.message-text {
font-size: 1.125rem;
font-weight: 500;
color: #374151;
margin: 0 0 0.5rem 0;
}
.count-text {
font-size: 0.875rem;
color: #6b7280;
margin: 0;
}
.loading-details {
margin-top: 1rem;
text-align: left;
}
.details {
font-size: 0.875rem;
}
.details-summary {
cursor: pointer;
color: #6b7280;
font-weight: 500;
list-style: none;
padding: 0.5rem 0;
border-bottom: 1px solid #e5e7eb;
}
.details-summary::-webkit-details-marker {
display: none;
}
.details-summary::before {
content: "▶";
display: inline-block;
margin-right: 0.5rem;
transition: transform 0.2s;
}
.details[open] .details-summary::before {
transform: rotate(90deg);
}
.details-list {
margin: 0.5rem 0 0 0;
padding: 0;
list-style: none;
}
.details-item {
padding: 0.25rem 0;
color: #6b7280;
border-bottom: 1px solid #f3f4f6;
}
.details-item:last-child {
border-bottom: none;
}
/* 다크 모드 지원 */
@media (prefers-color-scheme: dark) {
.loading-container {
background: #1f2937;
color: #f9fafb;
}
.message-text {
color: #f9fafb;
}
.count-text,
.details-summary,
.details-item {
color: #d1d5db;
}
.details-summary {
border-bottom-color: #374151;
}
.details-item {
border-bottom-color: #374151;
}
}
</style>

65
composables/useLoading.ts Normal file
View File

@@ -0,0 +1,65 @@
/**
* 로딩 상태를 쉽게 사용할 수 있는 컴포저블
* 로딩 카운터 방식으로 여러 비동기 작업을 안전하게 관리합니다.
*/
export const useLoading = () => {
const loadingStore = useLoadingStore();
/**
* 로딩 상태와 함께 비동기 함수를 실행합니다.
* 함수 실행 중에는 자동으로 로딩 카운터가 증가하고, 완료되면 감소합니다.
*
* @param asyncFn 실행할 비동기 함수
* @param message 로딩 메시지 (선택사항)
* @returns Promise<T> 비동기 함수의 결과
*/
const withLoading = async <T>(
asyncFn: () => Promise<T>,
message?: string
): Promise<T> => {
loadingStore.startLoading(message);
try {
return await asyncFn();
} finally {
loadingStore.stopLoading(message);
}
};
/**
* 로딩 상태를 수동으로 관리할 때 사용합니다.
*
* @param message 로딩 메시지 (선택사항)
* @returns 로딩 종료 함수
*/
const startLoading = (message?: string) => {
loadingStore.startLoading(message);
return () => loadingStore.stopLoading(message);
};
/**
* 특정 메시지로 로딩을 시작하고, 해당 메시지로 종료할 수 있는 함수를 반환합니다.
*
* @param message 로딩 메시지
* @returns 로딩 종료 함수
*/
const withMessage = (message: string) => {
loadingStore.startLoading(message);
return () => loadingStore.stopLoading(message);
};
return {
// 상태
isLoading: computed(() => loadingStore.isLoading),
loadingCount: computed(() => loadingStore.loadingCount),
currentMessage: computed(() => loadingStore.currentMessage),
loadingMessages: computed(() => loadingStore.loadingMessages),
// 액션
startLoading,
stopLoading: loadingStore.stopLoading,
withLoading,
withMessage,
clearAll: loadingStore.clearAllLoading,
reset: loadingStore.reset,
};
};

View File

@@ -21,7 +21,6 @@ export const usePermission = () => {
// 권한 데이터 직접 접근
permissions: computed(() => permissionsStore.permissions),
resources: computed(() => permissionsStore.permissions?.resources),
isLoading: computed(() => permissionsStore.isLoading),
// 리소스별 전체 접근 함수
getPageGroups: () =>

View File

@@ -0,0 +1,205 @@
<template>
<div
class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-12 px-4"
>
<div class="max-w-4xl mx-auto">
<!-- 페이지 헤더 -->
<div class="text-center mb-8">
<h1 class="text-4xl font-bold text-gray-900 mb-4">
로딩 카운터 테스트
</h1>
<p class="text-xl text-gray-600">
전역 로딩 시스템의 동작을 테스트할 있습니다
</p>
</div>
<!-- 현재 상태 표시 -->
<div class="bg-white p-6 rounded-lg shadow-lg mb-8">
<h2 class="text-2xl font-semibold mb-4">현재 로딩 상태</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div class="space-y-2">
<p>
<strong>로딩 :</strong>
<span :class="isLoading ? 'text-green-600' : 'text-red-600'">
{{ isLoading ? "예" : "아니오" }}
</span>
</p>
<p><strong>로딩 카운트:</strong> {{ loadingCount }}</p>
<p><strong>현재 메시지:</strong> {{ currentMessage }}</p>
</div>
<div class="space-y-2">
<p><strong>진행 중인 작업:</strong></p>
<ul
v-if="loadingMessages.length > 0"
class="list-disc list-inside space-y-1"
>
<li
v-for="(message, index) in loadingMessages"
:key="index"
class="text-sm"
>
{{ message }}
</li>
</ul>
<p v-else class="text-gray-500 text-sm">없음</p>
</div>
</div>
</div>
<!-- 테스트 버튼들 -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- 단일 로딩 테스트 -->
<div class="bg-white p-6 rounded-lg shadow-lg">
<h3 class="text-xl font-semibold mb-4">단일 로딩 테스트</h3>
<div class="space-y-3">
<button
class="w-full bg-blue-500 hover:bg-blue-600 disabled:bg-gray-400 text-white font-medium py-3 px-4 rounded-lg transition-colors"
:disabled="isLoading"
@click="testSingleLoading"
>
단일 작업 로딩 (2)
</button>
</div>
</div>
<!-- 다중 로딩 테스트 -->
<div class="bg-white p-6 rounded-lg shadow-lg">
<h3 class="text-xl font-semibold mb-4">다중 로딩 테스트</h3>
<div class="space-y-3">
<button
class="w-full bg-purple-500 hover:bg-purple-600 disabled:bg-gray-400 text-white font-medium py-3 px-4 rounded-lg transition-colors"
:disabled="isLoading"
@click="testMultipleLoading"
>
동시 다중 작업 (1, 2, 3)
</button>
<button
class="w-full bg-orange-500 hover:bg-orange-600 disabled:bg-gray-400 text-white font-medium py-3 px-4 rounded-lg transition-colors"
:disabled="isLoading"
@click="testSequentialLoading"
>
순차 다중 작업 ( 1초씩)
</button>
</div>
</div>
<!-- 권한 로딩 테스트 -->
<div class="bg-white p-6 rounded-lg shadow-lg">
<h3 class="text-xl font-semibold mb-4">권한 로딩 테스트</h3>
<div class="space-y-3">
<button
class="w-full bg-indigo-500 hover:bg-indigo-600 disabled:bg-gray-400 text-white font-medium py-3 px-4 rounded-lg transition-colors"
:disabled="isLoading"
@click="testPermissionLoading"
>
권한 데이터 로드
</button>
<button
class="w-full bg-pink-500 hover:bg-pink-600 disabled:bg-gray-400 text-white font-medium py-3 px-4 rounded-lg transition-colors"
:disabled="isLoading"
@click="testPermissionWithOtherLoading"
>
권한 + 다른 작업 동시 실행
</button>
</div>
</div>
<!-- 제어 버튼들 -->
<div class="bg-white p-6 rounded-lg shadow-lg">
<h3 class="text-xl font-semibold mb-4">로딩 제어</h3>
<div class="space-y-3">
<button
class="w-full bg-red-500 hover:bg-red-600 text-white font-medium py-3 px-4 rounded-lg transition-colors"
@click="clearAllLoading"
>
모든 로딩 강제 종료
</button>
<button
class="w-full bg-gray-500 hover:bg-gray-600 text-white font-medium py-3 px-4 rounded-lg transition-colors"
@click="resetLoading"
>
로딩 상태 리셋
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
const {
isLoading,
loadingCount,
currentMessage,
loadingMessages,
withLoading,
clearAll,
reset,
} = useLoading();
// 단일 로딩 테스트
const testSingleLoading = async () => {
await withLoading(async () => {
await new Promise(resolve => setTimeout(resolve, 2000));
}, "단일 작업 실행 중...");
};
// 동시 다중 작업 로딩 테스트
const testMultipleLoading = async () => {
const tasks = [
{ name: "작업 1", duration: 1000 },
{ name: "작업 2", duration: 2000 },
{ name: "작업 3", duration: 3000 },
];
// 모든 작업을 동시에 시작
const promises = tasks.map(task =>
withLoading(async () => {
await new Promise(resolve => setTimeout(resolve, task.duration));
}, `${task.name} 실행 중...`)
);
await Promise.all(promises);
};
// 순차 다중 로딩 테스트
const testSequentialLoading = async () => {
const tasks = ["작업 A", "작업 B", "작업 C"];
for (const task of tasks) {
await withLoading(async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
}, `${task} 실행 중...`);
}
};
// 권한 로딩 테스트
const testPermissionLoading = async () => {
const permissionsStore = usePermissionsStore();
await permissionsStore.fetchPermissions();
};
// 권한 + 다른 작업 동시 실행
const testPermissionWithOtherLoading = async () => {
// 권한 로딩과 다른 작업을 동시에 실행
await Promise.all([
usePermissionsStore().fetchPermissions(),
withLoading(async () => {
await new Promise(resolve => setTimeout(resolve, 1500));
}, "다른 작업 실행 중..."),
]);
};
// 로딩 제어 함수들
const clearAllLoading = () => {
clearAll();
};
const resetLoading = () => {
reset();
};
</script>

75
stores/loading.ts Normal file
View File

@@ -0,0 +1,75 @@
/**
* 전역 로딩 상태 관리 스토어 (로딩 카운터 방식)
* 여러 비동기 작업이 동시에 진행되어도 안전하게 로딩 상태를 관리합니다.
*/
export const useLoadingStore = defineStore(
"loading",
() => {
// 로딩 카운터 - 0보다 크면 로딩 중
const loadingCount = ref(0);
// 현재 로딩 중인 작업들의 메시지
const loadingMessages = ref<string[]>([]);
// 로딩 상태 (카운터가 0보다 크면 true)
const isLoading = computed(() => loadingCount.value > 0);
// 현재 로딩 메시지 (가장 최근 메시지 또는 기본 메시지)
const currentMessage = computed(
() =>
loadingMessages.value[loadingMessages.value.length - 1] || "로딩 중..."
);
// 로딩 시작
const startLoading = (message?: string) => {
loadingCount.value++;
if (message) {
loadingMessages.value.push(message);
}
};
// 로딩 종료
const stopLoading = (message?: string) => {
loadingCount.value = Math.max(0, loadingCount.value - 1);
if (message && loadingMessages.value.length > 0) {
const index = loadingMessages.value.lastIndexOf(message);
if (index > -1) {
loadingMessages.value.splice(index, 1);
}
} else if (loadingMessages.value.length > 0) {
// 메시지가 지정되지 않으면 가장 최근 메시지 제거
loadingMessages.value.pop();
}
};
// 모든 로딩 강제 종료
const clearAllLoading = () => {
loadingCount.value = 0;
loadingMessages.value = [];
};
// 로딩 상태 리셋
const reset = () => {
loadingCount.value = 0;
loadingMessages.value = [];
};
return {
// 상태
loadingCount: readonly(loadingCount),
loadingMessages: readonly(loadingMessages),
isLoading,
currentMessage,
// 액션
startLoading,
stopLoading,
clearAllLoading,
reset,
};
},
{
persist: false, // 로딩 상태는 새로고침 시 초기화되어야 함
}
);

View File

@@ -13,14 +13,11 @@ export const usePermissionsStore = defineStore(
},
});
// 권한 로딩 상태
const isLoading = ref(false);
// 서버에서 권한 데이터 가져오기 (현재는 가데이터 사용)
const fetchPermissions = async (): Promise<boolean> => {
try {
isLoading.value = true;
const { withLoading } = useLoading();
return await withLoading(async () => {
// 실제 API 호출 (백엔드 준비되면 주석 해제)
/*
const { success, data } = await useApi<UserPermissions>('/auth/permissions', {
@@ -53,12 +50,7 @@ export const usePermissionsStore = defineStore(
};
return true;
} catch (error) {
console.error("권한 데이터 로드 실패:", error);
return false;
} finally {
isLoading.value = false;
}
}, "권한 정보를 불러오는 중...");
};
const getPagePaths = (): string[] => {
@@ -104,7 +96,6 @@ export const usePermissionsStore = defineStore(
return {
permissions: readonly(permissions),
isLoading: readonly(isLoading),
fetchPermissions,
clearPermissions,