본문 바로가기

Vue.js

[Vue.js] 라이프사이클(Lifecycle)이란?

728x90

Vue.js는 Vue 컴포넌트의 생성부터 소멸까지 일련의 과정을 수반하는 여러 생명주기(Lifecycle) 훅을 제공합니다. 각 단계는 특정 작업을 수행할 수 있는 기회를 제공하며, 이를 적절히 활용하면 컴포넌트의 동작을 세밀하게 제어할 수 있습니다. Vue 생명주기에 대해 자세히 알아보겠습니다.

ex_screenshot

Vue 생명주기 훅(Lifecycle Hooks)

Vue 컴포넌트는 다음과 같은 순서로 생명주기 훅을 거칩니다:

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeDestroy
  8. destroyed

각 생명주기 훅의 역할

  1. beforeCreate:
    • 컴포넌트 인스턴스가 초기화된 후 호출됩니다.
    • 아직 데이터와 이벤트가 설정되기 전이므로, 이 단계에서는 datacomputed 프로퍼티에 접근할 수 없습니다.
    • new Vue({ beforeCreate() { console.log('beforeCreate'); } });
  2. created:
    • 인스턴스가 생성되고 데이터 관찰(data observation)과 이벤트/워처 설정이 완료된 후 호출됩니다.
    • data, methods, computed 등에 접근할 수 있습니다.
    • new Vue({ created() { console.log('created'); } });
  3. beforeMount:
    • 마운트가 시작되기 직전에 호출됩니다.
    • DOM이 생성되지 않았기 때문에 아직 템플릿 렌더링이 일어나지 않습니다.
    • new Vue({ beforeMount() { console.log('beforeMount'); } });
  4. mounted:
    • DOM에 컴포넌트가 마운트된 후 호출됩니다.
    • 템플릿을 렌더링한 후 DOM 요소에 접근할 수 있습니다.
    • new Vue({ mounted() { console.log('mounted'); } });
  5. beforeUpdate:
    • 데이터가 변경되어 DOM이 업데이트 되기 직전에 호출됩니다.
    • 변경된 데이터는 접근할 수 있지만, DOM이 아직 반영되지 않았습니다.
    • new Vue({ beforeUpdate() { console.log('beforeUpdate'); } });
  6. updated:
    • 데이터가 변경되어 DOM이 업데이트된 후 호출됩니다.
    • DOM이 변경된 후의 상태를 확인하거나 조작할 수 있습니다.
    • new Vue({ updated() { console.log('updated'); } });
  7. beforeDestroy:
    • 컴포넌트가 파괴되기 직전에 호출됩니다.
    • 아직 인스턴스가 완전히 제거되지 않았기 때문에 데이터와 메서드에 접근할 수 있습니다.
    • new Vue({ beforeDestroy() { console.log('beforeDestroy'); } });
  8. destroyed:
    • 컴포넌트가 파괴된 후 호출됩니다.
    • 모든 디렉티브와 이벤트 리스너가 해제되고, 하위 컴포넌트 인스턴스도 모두 파괴됩니다.
    • new Vue({ destroyed() { console.log('destroyed'); } });

Vue 생명주기 훅의 활용 예시

아래는 간단한 Vue 컴포넌트 예제입니다. 각 생명주기 훅에서 콘솔에 메시지를 출력하도록 설정합니다.

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello, Vue!'
    };
  },
  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>

결론

Vue 생명주기 훅은 컴포넌트의 초기화, 업데이트, 소멸 과정에서 특정 로직을 실행할 수 있는 중요한 도구입니다. 각 단계에서 어떤 작업을 수행할 수 있는지 이해하고, 이를 적절히 활용하면 컴포넌트의 동작을 더욱 세밀하게 제어할 수 있습니다. Vue 생명주기를 잘 활용하여 효율적이고 유지보수하기 쉬운 애플리케이션을 개발해보세요.

'Vue.js' 카테고리의 다른 글

[Vue.js] Vuex이란?  (1) 2024.06.13