본문 바로가기
Programming/Vue

[Vue] Vue의 Lifecycle

by 혀코 2022. 8. 29.

 

안녕하세요. 혀코입니다.

 

이번 시간에는 Vue Lifecycle에 대해서 알아보겠습니다.

 

Vue Lifecycle 은 다음과 같습니다.

 

Vue의 Lifecycle 다음과 같은 것 있습니다.

beforeCreate

created

beforeMount

mounted

beforeUpdate

updated

beforeUnmount

unmounted

 

이 중에서 beforeCreate, created, beforeMount, mounted의 차이점을 코드를 통해 알아보겠습니다.

 

<template>
  <h1 @click="increase">{{ count }}</h1>
  <p v-if="count > 5" @click="reset">5보다 큽니다!</p>
</template>

<script>
export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increase() {
      this.count += 1
    },
    reset() {
      this.count = 0
    }
  },
  beforeCreate() {
    console.log("beforeCreate", this.count)
    console.log("beforeCreate", document.querySelector('h1'))
  },
  created() {
    console.log("created", this.count)
    console.log("created", document.querySelector('h1'))
  },
  beforeMount() {
    console.log("beforeMount", this.count)
    console.log("beforeMount", document.querySelector('h1'))
  },
  mounted() {
    console.log("mounted", this.count)
    console.log("mounted", document.querySelector('h1'))
  }
}
</script>

 

코드를 실행시키면 다음과 같이 출력합니다.

 

 

App이 생성되기 전에 beforeCreate 을 실행했을 때 변수가 undefined이고 HTML에 연결이 되지않아 null 값을 가지고,

created lifecycle에서는 App이 생성된 후에 변수가 0으로 지정되었지만, HTML에 연결되지 않아 null 값을 가집니다.

beforeMount에서는 HTML에 연결되지 않아 null 값을 가지고 mounted에서는 HTML에 연결되어 <h1>0</h1> 값을 리턴합니다. 

 

이렇게 Vue의 Lifecycle에 대해서 알아봤습니다.

 

해당 정보가 도움이 되셨다면, 공감과 구독 부탁 드립니다.

 

감사합니다. :)

댓글