본문 바로가기
개발/Vue.js

Vue.js emit 이해 및 사용(자식컴포넌트 -> 부모컴포넌트 이벤트/데이터 전달)

by 궁즉변 변즉통 통즉구 2024. 3. 7.
반응형

vue에서 부모컴포넌트에서 자식컴포넌트로 데이터를 보내기 위해 props를 사용한다면, emit은 자식컴포넌트에서 부모컴포넌트로 이벤트나 데이터를 보내기 위해 사용한다. 

props와 emit

 

 

사용법을 이해하기 위한 간단한 샘플은 아래와 같다.

먼저 자식컴포넌트를 아래와 같이 작성해준다. mount가 되면 $emit을 사용하여 메시지를 전달한다.

<template>
  <div></div>
</template>
<script>
export default {
  data() {
    return {
      msg: "자식 컴포넌트 메시지",
    };
  },
  mounted() {
    // $emit을 사용하여 부모컴포넌트로 데이터(msg) 전달
    this.$emit("send-message", this.msg); 
  },
};
</script>

 

부모컴포넌트는 아래와 같이 작성해보자. 자식컴포넌트로부터 "send-message"를 받으면 부모컴포넌트 내부의 receiveMsg() 메소드를 호출한다.

<template>
  <!-- 자식컴포넌트로부터 'send-message'를 받으면 receiveMsg 메소드 호출 -->
  <EmitChildComponentVue @send-message="receiveMsg" />
</template>
<script>
// 자식 컴포넌트 import
import EmitChildComponentVue from "./EmitChildComponent.vue";

export default {
  components: { EmitChildComponentVue },
  methods: {
    receiveMsg(msg) {
      console.log("child msg: ", msg);
    },
  },
};
</script>

 

이제 부모컴포넌트를 적용해보면 아래와 같이 자식컴포넌트로부터 전달받은 메시지가 로그로 출력되는 것을 확인할 수 있다.

 

정리해보면 자식컴포넌트에서 $emit으로 부모컴포넌트에 선언된 "send-message" 이벤트를 호출한다.

this.$emit("send-message", this.msg);

 

부모컴포넌트에서는 "send-message" 이벤트가 호출되면 내부 receiveMsg()메소드를 호출한다.

<EmitChildComponentVue @send-message="receiveMsg" />

 

부모컴포넌트의 receiveMsg() 메소드가 호출된다.

methods: {
    receiveMsg(msg) {
        console.log("child msg: ", msg);
    },
},

 

반응형

댓글