라이프사이클에 대한 자세한 설명은 공식사이트에 기재 되어 있다.
vue 공식 사이트:
https://ko.vuejs.org/guide/essentials/lifecycle
https://ko.vuejs.org/api/options-lifecycle.html
크게 3단계로 보면된다
1. create 단계
- 데이터만 존재하는 단계 (HTML 생성 전)
2. mount 단계
- <template> 사이에 있던 것들을 실제 HTML 로 바꿔준다.
3. 컴포넌트 생성
- index.html 에 장착하는 단계
(4. 업데이트 단계)
- data가 변하면 HTML 이 재랜더링 된다. 실은 <컴포넌트>가 재랜더링 되는 것
=> 이 것을 업데이트라고 한다. - 컴포넌트 안의 data가 변할 때 업데이트 된다고 한다.
(5. unmount 단계)
- 컴포넌트가 삭제될 때 umount 된다고 한다.
우리는 이 단계들 중간에 훅을 걸 수 있다.
Lifecycle Hook 을 걸어서 중간에 원하는 코드를 실행할 수 있다.
📌 vue의 lifecycle hook 을 활용하기
1. 화면이 노출되고 2초 뒤에 Discount 영역 사라지게 하기
Discount 영역 state 를 관리하기 위해 showDiscount 를 데이터 보관함에 등록하고
HTML 영역엔 v-if 를 활용한다.
data() {
return {
menu : ['Home', 'Shop', 'About'],
count : [], // 신고 수
isModal : false,
originProdList : [...prodList], // 부동산 데이터 원본
prodList : [...prodList], // 부동산 데이터들
prodId : 0, // 상품 id
showDiscount : true
}
}
<!-- 할인 배너 영역 -->
<Discount v-if="showDiscount === true"/>
mounted 와 setTimeout 을 활용하였다.
// arrow fucntion 을 써야 this 를 활용할 수 있다.
mounted() {
setTimeout(() => {
this.showDiscount = false;
}, 2000)
}
⚡ arrow function 을 써야 this 를 활용할 수 있다!
2초 뒤에 할인 배너 영역이 사라졌다.
App.vue 에 mount() 를 사용하면 App.vue 가 mount 되고 나서 코드를 실행한다.
Modal.vue 에 mount() 를 사용하면 Modal.vue 가 mount 되고 나서 코드를 실행한다.
서버에서 데이터를 가져올 때도 lifecycle hook 안에 코드를 짠다.
보통 created(), mounted() 안에 작성한다.
2. Discount 영역의 % 를 1초에 -1% 씩 시키는 코드를 짜보자.
1. 먼저 Discount.vue 파일에서 percentage 의 숫자를 데이터보관함에 담는다.
data () {
return {
discountNum : 20
}
},
2. HTML 영역에서 데이터바인딩을 해주자
<template>
<div class="discount">
<h4>지금 결제하면 {{discountNum}}% 할인</h4>
</div>
</template>
3. Discount.vue 가 mounted 된 후 1초에 discountNum 을 -1 시킨다
setInterval 을 활용한다.
// Discount.vue
mounted() {
// 1초에 1% 감소, 0되면 stop
const decNum = setInterval(() => {
this.discountNum--;
if (this.discountNum === 0) {
clearInterval(decNum);
}
}, 1000);
}
setIterval 을 중지시키려면, setInterval 을 변수에 담고
clearInterval(변수); 를 실행시켜주면 된다.
화면이 로드된 후 1초마다 -1% 씩 감소하고, 0% 가 되면 멈추는 것을 확인할 수 있다.
'Vue3 > 코딩애플 part1' 카테고리의 다른 글
[Vue/코딩애플/part1] 12. 상품 정렬 기능 / 데이터 원본 보존 (0) | 2024.07.30 |
---|---|
[Vue/코딩애플/part1] 11. UI 애니메이션 효과 주기 / transition (0) | 2024.07.30 |
[Vue/코딩애플/part1] 10. input (v-model), watcher (0) | 2024.07.29 |
[Vue/코딩애플/part1] 9. custom event (자식이 부모 데이터 바꿀 때) (0) | 2024.07.29 |
[Vue/코딩애플/part1] 8. props (0) | 2024.07.29 |