티스토리 뷰

반응형

vue 생성 관련 내부 요소를 살펴보았으니,

vue component의 라이프 사이클을 휘리릭 정리해보자.


가장 정확하고 잘 설명된 곳 : https://kr.vuejs.org/v2/guide/instance.html#인스턴스-라이프사이클-훅


라이프사이클은 간단히 다음과 같은 순서다.


 created(vue 객체 생성) > mounted(vue 객체를 dom에 붙인 시점) > destroyed(vue 객체 삭제)


created와 destoyed는 이해하겠는데,

mounted 시점을 이해하기가 어려웠다.


하여 예시 코드를 보며 살펴보자.


<template>

    <div></div>

</template>


<script>

    export default {

        name: 'LifeCycle',


        data: function() {

            return {

            }

        },


        created() {

            console.log('vue component 생성', this.$el, this._isMounted)

        },


        mounted() {

            console.log('vue component dom에 그려짐', this.$el, this._isMounted)

        },


        destroyed() {

            console.log('vue component 삭제', this.$el, this._isMounted)

        }

    }

</script>


<style></style>


다음과 같이 vue 컴포넌트를 생성하고,

각 라이프사이클의 시점에 log를 찍도록 해보았다. 


* 참고

this.$el : vue 컴포넌트의 dom 객체.

this._isMounted : vue 컴포넌트가 dom에 그려졌는지(mount 되었는지) 여부 값 (true : 그려짐 / false : 아직 dom에 그려지지 않음)



결과는??


결과 로그를 통해 알 수 있 듯이,


created 시점에는 vue 객체가 생성만! 하고 (하여 vue의 dom 값이 undefined)

mounted 시점에는 vue 객체의 html이 실제 dom에 그려져 컴포넌트의 dom이 찍히는 것을 알 수 있다. 


그런데, 만약에 created 시점에 vue의 dom을 접근하고 싶다면 방법이 없는건 아니다. 

바로 우리에겐 nextTick이 있음!!!


그럼 nextTick을 어떻게 사용하는가 예시를 통해 보자.


<template>

    <div></div>

</template>


<script>

    export default {

        name: 'LifeCycle',


        data: function() {

            return {

            }

        },


        created() {

            console.log('vue component 생성', this.$el, this._isMounted)

            this.$nextTick(() => {

                console.log('in nextTick', this.$el, this._isMounted); 

            })

        },


        mounted() {

            console.log('vue component dom에 그려짐', this.$el, this._isMounted)

        },


        destroyed() {

            console.log('vue component 삭제', this.$el, this._isMounted)

        }

    }

</script>


<style></style>


위 코드의 결과는?? 


그렇군! 


nextTick 메소드는 mounted 메소드가 실행된 후에 실행되었다!!

또한 created 메소드 안에서 찍히지 않았던 this.$el 값이 nextTick 메소드 안에서는 찍힌다! 


즉, nextTick은 DOM 업데이트가 된 후에 콜백으로 선언된 함수가 실행하도록 돕는 메소드다.


이 메소드를 통해서 dom이 그려지기 전의 시점에서도 에러 없이 dom을 핸들링할 수 있다. 


nextTick과 관련된 상세 내용은 다음 참조

https://kr.vuejs.org/v2/api/#Vue-nextTick 

반응형

'정리하기 > vue.js' 카테고리의 다른 글

vue 다른 컴포넌트 끼리의 통신  (0) 2018.05.16
vue 컴포넌트 상속  (0) 2018.05.16
vue 선언 내부 살펴보기  (0) 2018.05.16
vue.js 프로젝트 내부 살펴보기  (0) 2018.05.15
vue.js  (0) 2018.05.15
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함