Vue.js에서 생명주기 훅(Lifecycle Hooks)은 컴포넌트의 생성, 렌더링, 업데이트, 소멸 등 다양한 단계에서 특정 동작을 수행할 수 있는 메서드입니다. 컴포넌트는 여러 가지 단계를 거치며 화면에 나타나고 없어지는데, 생명주기 훅은 이러한 단계에서 코드가 실행되도록 해 줍니다.
beforeCreate
data, computed, methods, watch 등이 설정되지 않은 상태입니다.beforeCreate() {
console.log('컴포넌트가 생성되기 전에 호출됨');
}
created
data와 methods가 설정되고 접근 가능해집니다.created() {
console.log('컴포넌트가 생성되었습니다.');
}
beforeMount
beforeMount() {
console.log('컴포넌트가 마운트되기 전에 호출됨');
}
mounted
mounted() {
console.log('컴포넌트가 마운트되었습니다.');
}
beforeUpdate
beforeUpdate() {
console.log('데이터가 업데이트되기 직전');
}
updated
updated() {
console.log('데이터가 업데이트된 후 DOM이 갱신되었습니다.');
}
beforeDestroy
beforeDestroy() {
console.log('컴포넌트가 파괴되기 직전입니다.');
}
destroyed
destroyed() {
console.log('컴포넌트가 파괴되었습니다.');
}
export default {
data() {
return {
message: 'Hello Vue!'
};
},
beforeCreate() {
console.log('beforeCreate: 인스턴스가 초기화되기 전');
},
created() {
console.log('created: 인스턴스가 생성된 후');
},
beforeMount() {
console.log('beforeMount: DOM이 마운트되기 전');
},
mounted() {
console.log('mounted: DOM이 마운트된 후');
},
beforeUpdate() {
console.log('beforeUpdate: 데이터가 업데이트되기 전');
},
updated() {
console.log('updated: 데이터가 업데이트된 후');
},
beforeDestroy() {
console.log('beforeDestroy: 컴포넌트가 파괴되기 전');
},
destroyed() {
console.log('destroyed: 컴포넌트가 파괴된 후');
}
};
이러한 생명주기 훅을 적절히 활용하면 컴포넌트의 다양한 상태 변화에 따라 동작을 제어할 수 있습니다.
