Vue 3.0/02.Essentials

[vue 3] 12.Vue 객체의 라이프 사이클

  • -
반응형

이번 포스트에서는 상당히 길고 복합한 Vue 객체의 라이프 사이클에 대해서 살펴보자.

이미지출처:https://www.quora.com/What-is-the-human-life-cycle

 

Vue 객체의 라이프 사이클

Vue 객체는 beforeCreate에서 부터 unmounted까지 여러 단계를 거쳐 사용되는데 각 단계별로 hook을 이용해서 부가적으로 처리할 일들을 작성할 수 있다.

composition api를 사용하는 경우에는 setup hook에서 beforeCreate, created에 해당하는 과정이 한꺼번에 처리된다. 이제까지 코드를 작성하면서 써온 setup() 메서드가 바로 setup hook 이다.

 

life cycle hook

composition api를 사용할 경우 각각의 hook은 setup() 내부에서 onXX의 형태로 접근할 수 있다.

라이프 사이클 훅
(Options API)
Setup 내부에서의 호출
(Composition API)
설명
beforeCreate X created 호출 전
created X Vue 객체가 생성된 후 데이터에 대한 관찰 기능
beforeMount onBeforeMount Componentreactive state에 대한 설정을 끝낸 상태이며 마운트가 시작되기 전에 호출
mounted onMounted Componentmount 된 후 호출되며 DOM과 관련된 부가 수행 가능
 - 모든 자식 component들도 mount 완료 상태
 - DOM 트리가 완성되어 부모 container에 삽입 완료된 상태
beforeUpdate onBeforeUpdate 가상 DOM이 렌더링, 패치되기전에 데이터가 변경될 때 호출
이 단계에서 추가적인 상태 변경을 수행할 수 있지만 다시 렌더링 되지는 않음
updated onUpdated 데이터 변경으로 가상 DOM이 다시 렌더링 되고 패치된 후에 호출됨
이 훅이 호출된 시점은 컴포넌트의DOM이 업데이트된 상태이므로 DOM에 종속적인 작업 가능
beforeUnmount onBeforeUnmount Vue 객체가 제거되기 전에 호출
unmounted onUnmounted Componentunmount 된 후에 호출
 - 모든 자식  component들도 unmount
 - setup 과정에서 생성된 반응성 효과(computed, watcher 포함) 중지
 - 사용자 정의로 작성했던 timer 등에 대한 중지 처리

정리된 내용을 살펴보면 여러가지 hook이 있지만 딱히 "이런 상황에서 엄청 유용하겠다."라는 내용은 보이지 않는다. 특히 composition api의 경우 setup에서 created를 처리하는데 일반적으로 ajax를 통한 정보 fetch의 행위가 이뤄지는 부분이 바로 이 부분이다.

 

life cycle hook 사용

간단한 예제를 통해 life cycle hook을 사용해보자.

  <script>
    const {createApp, ref, computed, watch, onMounted, onUpdated, onUnmounted} = Vue;
    const app = createApp({
      setup(props) {
        const num = ref(10);
        const plus = () => num.value++;

        const unmount = () => {
          app.unmount();
        };
        // num은 준비 되었지만 아직 DOM tree는 준비되지 않음
        console.log(
          `setup: num:  ${num.value}, , html: ${document.querySelector("#app").innerHTML
          }`
        );

        // num과 DOM tree가 준비됨 - DOM에 대한 갱신 작업 가능
        onMounted(() => {
          console.log(
            `onMounted: num:  ${num.value}, , html: ${document.querySelector("#app").innerHTML
            }`
          );
        });
        
        // num이 변경되어 DOM을 갱신함
        onUpdated(() => {
          console.log(
            `onUpdated: num:  ${num.value}, , html: ${document.querySelector("#app").innerHTML
            }`
          );
        });

        onUnmounted(() => {
          console.log(
            `onUnmounted: num:  ${num.value}, , html: ${document.querySelector("#app").innerHTML
            }`
          );
        });

        return {
          num, plus, unmount, computedNum,
        };
      },
    });
    app.mount("#app");
  </script>

이제 간단한 template을 통해서 vue 객체를 생성, mount, update, unmount 시켜보자.

<div id="app">
  <span>{{num}}</span>
  <button @click="plus">+</button>
  <button @click="unmount">unmount</button>
</div>

동작의 결과 아래와 같은 로그를 확인할 수 있다.

 

 

fetch 적용

일반적으로 ajax를 통해서 원격지의 데이터를 가져와서 활용할 경우는 created life cycle hook에서 처리한다.(왜냐햐면 데이터에 대한 이야기가 가능한 곳이기 때문이다.) 하지만 composition에서는 setup에서 created를 포함하기 때문에 그냥 setup 에서 처리하면 된다.

<script>
  const { createApp, reactive, toRefs } = Vue;

  createApp({
    setup() {
      const status = reactive({
        items: [],
        heavy: "",
      });
      fetch("server_url")
        .then((res) => res.json())
        .then((json) => (status.items = json.content));

      fetch("server_url")
        .then((res) => res.text())
        .then((text) => (status.heavy = text));

      return { ...toRefs(status) };
    },
  }).mount("#app");
</script>

 

composition api를 사용하다 보니 정말 life cycle hook에 대한 고민이 훨씬 없어지는것 같다.

반응형

'Vue 3.0 > 02.Essentials' 카테고리의 다른 글

[vue 3] 14.Try Yourself!!  (0) 2023.08.22
[vue 3] 13.app의 config 객체  (0) 2022.07.05
[vue 3] 11.watch  (0) 2022.07.03
[vue 3] 10.computed  (0) 2022.07.02
[vue 3] 09.DOM 요소에 직접 접근  (0) 2022.06.28
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.