LifeCycle Hooks에는 크게 Creation(생성), Mounting(장착), Updating(변경), Destruction(소멸) 이렇게 4단계가 있으며 이번에는 장착 단계에서도 onMounted를 중점으로 Mounting(장착) 단계에 대해 알아보려한다.

 

 

Mounting(장착) 단계는 DOM에 컴포넌트를 삽입하는 단계이며, onBeforeMount와 onMounted가 있다.

  • 서버 렌더링에서 지원하지 않는다.
  • 초기 렌더링 직전에 돔을 변경하고자 한다면 이 단계에서 활용할 수 있다.

onBeforeMount

: 컴포넌트가 마운트되기 직전에 호출된다

 

onMounted

: 컴포넌트가 마운트된 후에 호출되며 DOM에 접근할 수 있는 단계이다. 또한, 모든 자식 컴포넌트가 마운트된 상태를 의미한다.

 

위에서 정의내린 onBeforeMount와 onMounted 단계를 아래 코드를 통해 차이를 알아보면

onMounted는 컴포넌트가 mounted 된 이후이기 때문에 접근이 가능하지만 beforeMount 에서는 mount가 완료되지 않아 null 값이 출력 되는 것을 볼 수 있다.

 

<template>
    <div>
        <input ref="inputRef" type="text">
    </div>
</template>

<script>
import { onBeforeMount, onMounted, ref } from 'vue';

export default {
    setup() {
        console.log('setup')
        const inputRef = ref(null)
        onBeforeMount(() => {
            console.log('onBeforeMount', inputRef.value);
        });
        onMounted(() => {
            console.log('onMounted', inputRef.value);
        });
        return { inputRef }
    }
}
</script>


추가적으로, 자식 컴포넌트를 하나 추가하여 자식 컴포넌트에서 Mounting 순서를 같이 출력해보면 부모 컴포넌트에서 먼저 setup 과 onBeforeMount 작업이 실행되고 자식 컴포넌트에서 mounted가 마무리 된 이후에 부모 컴포넌트 mounted 작업이 완료되는 것을 볼 수 있다.

 

Child Components

<template>
    <div>

    </div>
</template>

<script>
import { onBeforeMount, onMounted } from 'vue'
export default {
    setup() {
        console.log('[Child] setup')
        onBeforeMount(() => {
            console.log('[Child] onBeforeMount')
        })
        onMounted(() => {
            console.log('[Child] onMounted')
        })

        return {}
    }
}
</script>

 

Parent Components

<template>
    <div>
        <input ref="inputRef" type="text">
        <LifeCycleChildVue></LifeCycleChildVue>
    </div>
</template>

<script>
import { onBeforeMount, onMounted, ref } from 'vue';
import LifeCycleChildVue from './components/LifeCycleChild.vue';

export default {
    components: {
        LifeCycleChildVue,
    },
    setup() {
        console.log('setup')
        const inputRef = ref(null)
        onBeforeMount(() => {
            console.log('onBeforeMount', inputRef.value);
        });
        onMounted(() => {
            console.log('onMounted', inputRef.value);
        });
        return { inputRef }
    }
}
</script>

<style lang="scss" scoped></style>

 

부모/자식 컴포넌트 Mounting 순서 출력 결과

 

 

이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.

 

 

반응형

'프로그래밍 > Vue' 카테고리의 다른 글

[Vue3] Computed  (0) 2024.04.26
Vue.js 2.0 라이프 사이클  (0) 2024.02.21
[Vue.js] Props 란  (0) 2022.06.30
구구단 게임  (0) 2020.07.13

+ Recent posts