어떤 Vue 인스턴스나 컴포넌트가 생성될 때, 미리 사전에 정의된 몇 단계의 과정을 거치게 되는데 이를 라이프사이클(lifecycle)이라 합니다. 다시 말해, Vue 인스턴스가 생성된 후 우리 눈에 보여지고, 사라지기까지의 단계를 일컫는 말입니다.
공식 문서에서
Vue 인스턴스는 크게 생성(create)되고,
DOM에 부착(mount)되고,
업데이트(update)되며,
없어지는(destroy) 4가지 과정을 거칩니다.
이 과정에서 Vue는 각각의 단계에서, Vue를 사용하는 사람들을 위해 훅(Hook)을 할 수 있도록 API를 제공합니다. 일반적으로 많이 사용하는 종류로는 beforeCreate, created, beforeMount, mounted, 가 있습니다. 이제 각각의 단계가 언제 발생하며, 어떤 특징을 가지고 있는지에 대해 알아봅니다.
this 사용 불가 왜?
app을 생성하기 직전이라서
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
befroeCreate(){//만들어지기 전
console.log('beforeCreate!',this.msg)//this 사용 불가 왜?
//app을 생성하기 직전이라서
console.log(document.querySelector('h1'))//null
},
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>
vue js app이 만들어진 직후
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
created(){
//vue js app이 만들어진 직후
console.log('created',this.msg)
console.log(document.querySelector('h1'))//null
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
beforeMount(){
console.log('beforeMount',this.msg)
console.log(document.querySelector('h1'))//null
//활용도 낮음
},
console.log(document.querySelector('h1'))//null
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>
html 구조와 연결된 직후! created의 차이를 완벽하게 숙지!
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
mounted(){
//html 구조와 연결된 직후! created의 차이를 완벽하게 숙지!
console.log('Mounted!',this.msg)
console.log(document.querySelector('h1'))
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
beforeUpdate(){
console.log('beforeUpdate!',this.msg)
console.log(document.querySelector('h1').textContent)
// // vm.msg='bye?' 를하면 hello Vue!
},
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>
<body>
<div id="app">
<h1>{{ msg }}</h1>
</div>
<script>
const App ={
data(){
return{
msg: 'Hellog Vue!'
}
},
// updated(){
// console.log('updated!',this.msg)
// console.log(document.querySelector('h1').textContent)
// // vm.msg='bye?' 를하면 hello Vue!
// }
const app =Vue.createApp(App)//애플리케이션 객체반환
const vm=app.mount('#app')//html과 연결 후 vue인스턴스 반환
</script>
</body>