Vue 인스턴스 생명주기 개요
Vue 인스턴스가 생성되어 종료될 때까지의 전체 과정을 생명주기(Lifecycle)라고 합니다. 이 과정 동안 총 8개의 특정 시점에 실행되는 훅(Hook) 함수를 제공합니다.
이러한 생명주기 훅은 관점 지향 프로그래밍(AOP) 개념과 유사하며, Django의 매직 메서드처럼 미리 정의된 시점에 개발자가 원하는 로직을 삽입할 수 있는 구조를 제공합니다.
생명주기 훅 함수 목록
| 훅 함수 | 실행 시점 | 주요 용도 |
|---|---|---|
| beforeCreate | 인스턴스 생성 전 | |
| created | 인스턴스 생성 후 | AJAX 요청, 데이터 초기화 |
| beforeMount | DOM 렌더링 전 | |
| mounted | DOM 렌더링 후 | |
| beforeUpdate | 데이터 업데이트 후 재렌더링 전 | |
| updated | 재렌더링 완료 후 | DOM 조작 필요 시 |
| beforeDestroy | 인스턴스 소멸 전 | 타이머 해제, 리소스 정리 |
| destroyed | 인스턴스 소멸 후 |
훅 함수 구현 예제
<script>
new Vue({
el: '#root',
data: {},
methods: {},
created() {
// 초기화 로직 작성
}
})
</script>
훅 함수 동작 확인 예제
전체 코드 보기
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>생명주기 테스트</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body>
<div id="app">
<button @click="toggleComponent">컴포넌트 표시/숨김</button>
<div v-if="isVisible">
<lifecycle-demo></lifecycle-demo>
</div>
</div>
<script>
Vue.component('lifecycle-demo', {
template: `
<div>
<button @click="modifyData">데이터 변경</button>
<span>{{ message }}</span>
</div>
`,
data() {
return {
message: '초기값'
}
},
methods: {
modifyData() {
this.message = '변경됨'
}
},
beforeCreate() {
console.group('beforeCreate 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
created() {
console.group('created 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
beforeMount() {
console.group('beforeMount 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
mounted() {
console.group('mounted 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
beforeUpdate() {
console.group('beforeUpdate 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
updated() {
console.group('updated 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
beforeDestroy() {
console.group('beforeDestroy 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
},
destroyed() {
console.group('destroyed 훅')
console.log('엘리먼트:', this.$el)
console.log('데이터:', this.$data)
console.log('속성값:', this.message)
console.groupEnd()
}
})
new Vue({
el: '#app',
data: {
isVisible: false
},
methods: {
toggleComponent() {
this.isVisible = !this.isVisible
return this.isVisible
}
}
})
</script>
</body>
</html>