컴포저블(Composables) 함수로 로직 재사용하기
여러 컴포넌트에서 완전히 똑같은 기능(예: 마우스 커서 위치 추적, 다크 모드 토글, API 데이터 패칭)을 작성하고 있다면 어떨까요? Vue 3에서는 이 중복된 기능(상태+로직)을 싹둑 잘라내어 별도의 함수로 빼낼 수 있습니다. 이를 컴포저블(Composables)이라고 부르며, 관례적으로 use...() 라는 이름으로 시작합니다.
<!-- ==========================================
// 📂 1. composables/useMouse.js (마우스 좌표 추적 훅)
// ⚠️ 주의: 실제 .js 파일에서는 <script> 태그를 작성하지 않습니다.
// ========================================== -->
<script>
import { ref, onMounted, onUnmounted } from 'vue';
export function useMouse() {
// [1. 상태]
const x = ref(0);
const y = ref(0);
// [2. 이벤트 핸들러 로직]
function update(event) {
x.value = event.pageX;
y.value = event.pageY;
}
// [3. 생명주기를 활용한 자동 설정]
// 컴포넌트가 화면에 뜰 때 마우스 추적 시작
onMounted(() => window.addEventListener('mousemove', update));
// 컴포넌트가 사라질 때 이벤트 정리 (메모리 누수 방지)
onUnmounted(() => window.removeEventListener('mousemove', update));
// [4. 결과 반환]
return { x, y };
}
</script>
<!-- ==========================================
// 📂 2. App.vue (컴포저블 가져다 쓰기)
// ========================================== -->
<script setup>
// 공통 로직을 한 줄로 불러옵니다.
import { useMouse } from './composables/useMouse';
// 이 컴포넌트 전용으로 독립된 마우스 x, y 값을 얻어냅니다.
const { x, y } = useMouse();
</script>
<template>
<div class="h-screen w-full flex items-center justify-center bg-teal-50">
<div class="text-center">
<h1 class="text-3xl font-bold text-teal-800 mb-4">현재 마우스 위치</h1>
<p class="text-4xl font-mono text-teal-600 bg-white p-4 rounded-xl shadow-lg border border-teal-200">
X: {{ x }} / Y: {{ y }}
</p>
</div>
</div>
</template>