본문 바로가기

JavaScript/Vue.js

[Vue.js] 컴포넌트 통신(props, event emit)

디렉티브에 이어서 잘 알아둬야 할 주제를 가져왔다.

바로 컴포넌트 통신 방식인 props와 event emit이다.

 

먼저 알아볼 props 속성은 상위 컴포넌트에서 하위 컴포넌트로 데이터를 전달할 수 있다.

간단한 예제로 확인해봐야겠다.

 

var childComponent = {
    template: '<div>{{ message }}</div>',
    props: ['message']
}

new Vue({
    el: '#app',
    components: {
        'child': childComponent
    },
    data: {
        pMessage: 'parent',
    }
});

 

<div id="app">
    <child :message="pMessage"></child>
</div>

 

child 컴포넌트로 메시지를 출력하는 예제이다.

특징은 child 컴포넌트에 props 속성을 정의하였고

상위 컴포넌트인 root 컴포넌트의 pMessage 데이터를 전달받아서 출력하였다.

 

props의 연결은 v-bind 디렉티브로 할 수 있다.

v-bind:프롭스 속성명="상위 컴포넌트의 데이터명"  형태로 정의하며 v-bind는 약어 ':'로 대체할 수 있다.

 


event emit은 무엇일까?

하위 컴포넌트에서 상위 컴포넌트로 이벤트를 전달할 수 있는 방식이다.

props 속성의 반대 개념으로 이해하면 되겠다.

 

간단한 예제로 확인해봐야겠다.

 

var childComponent = {
    template: '<button @click="btnEvent">button</button>',
    methods: {
        btnEvent: function() {
            this.$emit('child-event');
        }
    }
}

new Vue({
    el: '#app',
    components: {
        'child': childComponent
    },
    methods: {
        parentEvent: function() {
            console.log('event emit');
        }
    }
});

 

<div id="app">
    <child @child-event="parentEvent"></child>
</div>

 

child 컴포넌트로 버튼을 출력하는 예제이다.

버튼에 v-on 디렉티브를 활용하여 이벤트를 연결하고

그 이벤트 메서드에 this.$emit('이벤트명') 형태로 정의하여 event emit을 만들 수 있다.

 

event emit은 이벤트 연결이므로 v-on 디렉티브를 사용한다.

v-on:하위 컴포넌트에서 발생한 이벤트명="상위 컴포넌트의 메서드명" 형태로 정의하고 v-on은 약어 '@'로 대체할 수 있다.

event emit을 통하여 하위 컴포넌트의 이벤트로 상위 컴포넌트의 메서드를 실행시킬 수 있다.

 


 

간단하게 알아봤지만 컴포넌트 통신 방식을 다양하게 활용할 수 있을 것 같다.

자주 헷갈릴 것 같아서 기본적인 내용 위주로 정리해봤다.

 

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

[Vue.js] Vue 디렉티브(Directives)  (0) 2022.08.28
[Vue.js] 데이터 바인딩(data binding)  (0) 2022.08.21
[Vue.js] Vue 시작하기  (0) 2022.08.21