라이프사이클 훅은 컴포넌트 생애의 특정 시점(생성, DOM에 마운트, 업데이트, 제거)에 코드를 실행하게 해줍니다. Composition API에서는 setup 내부에서 호출하는 함수입니다.
주요 훅의 순서
vue
<script setup>
import { onMounted, onUpdated, onUnmounted, ref } from "vue";
const data = ref(null);
onMounted(() => {
// 컴포넌트가 이제 DOM에 있음 — 데이터 페칭, 요소 접근, 라이브러리 초기화
fetchData().then(d => (data.value = d));
});
onUpdated(() => {
// 반응형 변경으로 DOM이 다시 렌더링된 후 실행
});
onUnmounted(() => {
// 컴포넌트가 제거되는 중 — 여기서 정리(CLEAN UP)
clearInterval(timer);
window.removeEventListener("resize", handler);
});
</script>
