Front

Vue 컴포넌트 생명주기 이해하기

Z00_HWAN_99 2024. 10. 16. 12:30
728x90
반응형

라이프 사이클 훅(Life Cycle Hook)

  • Vue.js 프레임 워크에서 컴포넌트는 생성되고 파괴될때까지 여러 단계(생명주기)를 거치면서 특정 기능과 역할을 하는 함수를 호출할 수 있도록 설계되어 있다.
  • 그러한 함수를 훅 이라고 한다.
  • 컴포넌트에서 호출되는 함수를 라이프 사이클 훅이라고 한다.

라이프 사이클 훅 예제 코드

<script>
export default{
beforeCreate(){
console.log('beforeCreate');
},
created(){
console.log('created');
},
beforeMount(){
console.log('beforeMount');
},
mounted(){
console.log('mounted');
},
beforeUpdate(){
console.log('beforeUpdate');
},
updated(){
console.log('updated');
},
beforeUnmount(){
console.log('beforeUnmount');
},
unmounted(){
console.log('unmounted');
},
}
</script>

<template>
 
</template>

<style scoped>
 
</style>

이렇게 하고 나서 직접 개발자도구를 통해 console에 찍힌 것을 보면 8개가 아닌 beforeCreate, created, beforeMount, mounted 이렇게 4개가 나오게 된다. 그러면 아래와 같이 작성해보자

 

<script>
import FirstChild from './components/FirstChild.vue';//FirstChild 컴포넌트를 지역등록하기 위해 불러온다

export default{
components : {
FirstChild//불러온 FirstChild 컴포넌트를 components 옵션 속성으로 지역 등록
},
data(){
return {
visible : true,//visible 데이터를 정의하고 초기값으로 true 할당
};
},
beforeCreate(){
console.log('beforeCreate');
},
created(){
// console.log('created');
setTimeout(()=>{
this.visible = false;//컴포넌트가 생성된 후 3초 뒤에 visible이라는 데이터 값을 fasle로 재할당
}, 3000);
},
beforeMount(){
console.log('beforeMount');
},
mounted(){
console.log('mounted');
},
beforeUpdate(){
console.log('beforeUpdate');
},
updated(){
console.log('updated');
},
beforeUnmount(){
console.log('beforeUnmount');
},
unmounted(){
console.log('unmounted');
},
}
</script>

<template>
<FirstChild v-if="visible"></FirstChild>
</template>

<style scoped>
 
</style>

App.vue의 코드

<script>
export default{
beforeUnmount(){
console.log('beforeUnmount');
},
unmounted(){
console.log('unmounted');
},
}
</script>
<template>
<h1>컴포넌트1</h1>
<p>First Component</p>
</template>
<style scoped>
h1{
color: red;
}
p{
color: red;
}
</style>

FirstChild.vue 코드

 

App 컴포넌트의 beforeUpdate() 호출된 이후, 리렌더링과 패치과정이 거치면서 FirstChild 컴포넌트가 DOM에서 제거되는 과정을 할 수 있다. FirstChild의 beforeMount(), unmount() 훅이 호출되고, 이후 App 컴포넌트의 updated()훅이 호출되면 컴포넌트는 다시 마운트 상태에 진입한다.

 

ref

  • 뷰에서도 문서객체(DOM)을 참조할때나, 컴포넌트를 참조할 때 사용하는 속성.
  • script와 template 태그에 사용된 HTML 태그의 문서객체에 접근할 때 document 객체를 사용한다.
<script>
export default{
mounted(){
const dom1 = this.$refs.dom1;
const text = dom1.innerText;
console.log(text);
},
}
</script>

<template>
<h1 ref="dom1">h1 입니둥</h1>
</template>

<style scoped>
 
</style>
  • h1 태그의 innerText는 "h1 입니둥" 이다.
  • h1의 참조값을 얻으려면 컴포넌트가 마운트 될 때, 어플리케이션 인스턴스의 $refs 객체 속성으로 DOM 참조가 저장된다.
  • 저장된 참조값은 $refs 객체에 접근해서 사용할 수 있다.
  • 주의할 점 : $refs로 DOM에 대한 참조를 할 때는 컴포넌트가 마운트 후에 접근해야 한다.
  • $refs의 참조 횟수 제한은 없다. 이름만 중복되지 않으면 괜찮다.
728x90
반응형

'Front' 카테고리의 다른 글

Vue 컴포넌트의 데이터 효율적으로 다루기  (0) 2024.10.16
Vue component에 속성과 이벤트 정의  (0) 2024.10.16
Vue 컴포넌트 다루기  (2) 2024.10.16
Vue.JS로 Calculator 만들어보기  (0) 2024.10.16
Vue 폼 다루기  (6) 2024.10.15