Lifecycle Hooks

각 vue 인스턴스는 생성과 소멸의 과정 중 단계별 초기화 과정을 거친다.

각 단계가 트리거가 되어 특정 로직을 실행할 수 있는데, 이를 lifecycle hook라고 한다.

 

 

beforeCreate, created, beforeMount, mounted, beforeDestroy, destroyed 같은 hook에 원하는 로직을 실행 할 수 있다.

 

<template>
  <div>
    value : {{ value }}
    <button @click="changeValue">change value</button><br>
  </div>
</template>

<script>
export default {
  name:'ChildComponent',
  data() {
    return {
      value: 0,
    }
  },
  methods: {
    changeValue() {
      this.value = this.value + 1
    }
  },
  beforeCreate() {
    console.log('beforeCreate')
  },
  created() {
    console.log('created')
  },
  beforeMount() {
    console.log('beforeMount')
  },
  mounted() {
    console.log('mounted')
  },
  beforeUpdate() {
    console.log('beforeUpdate')
  },
  updated() {
    console.log('updated')
  },
  beforeDestroy() {
    console.log('beforeDestroy')
  },
  destroyed() {
    console.log('destroyed')
  }
}
</script>

<style>

</style>

run serve 하면 beforeCreate부터 mounted까지 실행된다.

changeValue 버튼을 클릭하면 beforeUpdate, updated 실행된다.

toggle 버튼 클릭하면 beforeDestroy, destroyed 실행되고, 

다시 클릭하면 beforeCreate, created, beforeMount, mounted 실행된다.

 

 

created

vue instance가 생성된 후 호출된다.

data, computed 등의 설정이 완료된 상태이다.

서버에서 받은 데이터를 vue instance의 data에 할당하는 로직을 구현하기 적합하다.

단, mount 되지 않아 요소에 접근할 수 없다.

created()에 어떤 함수를 추가하면, 이벤트없이 첫 실행시에 함수를 실행하도록 한다.

 

 

mounted

vue instance가 요소에 mount 된 후에 호출된다.

mount된 요소를 조작할 수 있다.

created의 경우 mount 되기 전이기 때문에 DOM에 접근할 수 없어서 querySelector 등이 동작하지 않는다.

 

 

updated

데이터가 변경되어 DOM에 변화를 줄 때 호출된다.

 

 

instance마다 각각의 lifecycle을 가지고 있다.

lifecycle hooks는 컴포넌트별로 정의할 수 있다.

 

 

App.vue 생성

-> childComponent.vue 생성

-> Childcomponent 부착(mount)

-> App 부착(mount)

-> childComponent 업데이트

순으로 동작했다.