props, emit을 통한 데이터 전달

이제 상위 Component에서 하위 Component로 데이터를 전달해 보겠습니다.
데이터를 받은 하위 Component는 데이터를 표시하거나 가공할 수 있습니다.

상위 Component에서 하위 Component로 데이터 전달

<html>
    <head>
        <title>뷰 props</title>
    </head>
    <body>
        <div id="app">
            <button>전역 컴포넌트 등록</button>
            <child-component v-bind:propsdata="message"></child-component>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.15/dist/vue.min.js"></script>
        <script>
            /* 하위 컴포넌트 선언 */
            Vue.component('child-component',{
                props : ['propsdata'],              
                template : '<p> {{ propsdata }} </p>'
            });
            /* 뷰 인스턴스 생성 */
            new Vue({
                el : '#app',
                data : {
                    message : 'Hello Vue!'
                }
            });
        </script>
    </body>
</html>

위 예제에서는 상위 Component를 지정하지 않았지만 존재하는 것처럼 보여지고 있습니다.
Vue는 Component를 등록함과 동시에 Vue Instance 자체가 상위 Component가 됩니다.
이를 최상위 Component로 부르기도 합니다.

상위 Component에서는 message로 인사말을 지정했습니다.
하위 Component에서는 상위 Component의 message의 속성값을 propsdata라는 이름으로 받았습니다.
이를 props에서 정의 해주고 template 속성에서 뿌려주게 됩니다.

하위 Component에서 상위 Component로 이벤트 전달

props는 상위 Component에서 하위 Component로 데이터를 전달했습니다.
이와 반대로 하위 Component에서 상위 Component로 데이터를 전달하려면 이벤트를 발생시켜 전달합니다.

<html>
    <head>
        <title>뷰 emit</title>
    </head>
    <body>
        <div id="app">
            <button>전역 컴포넌트 등록</button>
            <child-component v-on:show-log="printText"></child-component>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.15/dist/vue.min.js"></script>
        <script>
            /* 하위 컴포넌트 생성 */
            Vue.component('child-component',{               
                template : '<button v-on:click="showLog">show</button>',
                methods : {
                    showLog : function () {
                        this.$emit('show-log');
                    }
                }
            });
            /* 뷰 인스턴스 생성 */
            new Vue({
                el : '#app',
                data : {
                    message :'Hello Vue!'
                },
                methods : {
                    printText : function() {
                        console.log('received an event!');
                    }
                }
            });
        </script>
    </body>
</html>

show 버튼을 클릭하면 해당 Component에 있는 showLog 메소드가 실행됩니다.
showLog 메소드는 show-log 이벤트가 발생됩니다.
show-log 이벤트는 하위 Component에 정의한 show-log로 전달됩니다.
show-log 이벤트의 대상인 상위 Component의 printText 메소드가 실행됩니다.

이처럼 props와 emit를 이용하면 쉽게 상/하위 Component간의 데이터를 전달할 수 있습니다.