본문 바로가기
  • 일하면서 배운 내용 끄적이는 블로그
Vue

emit으로 자식 -> 부모 데이터 전달

by dhl7799 2024. 5. 3.

Vue에서 emit은 자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달하는 방법이다

 

예시

 

자식컴포넌트

<template>
  <div>
    <h2>자식 컴포넌트</h2>
    <button @click="sendMessageToParent">메시지 전송</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendMessageToParent() {
      const message = '안녕하세요, 부모님!';
      this.$emit('child-event', message);
    }
  }
};
</script>

 

부모 컴포넌트

<template>
  <div>
    <h1>부모 컴포넌트</h1>
    <ChildComponent @child-event="handleChildEvent" />
    <p>부모 컴포넌트에서 받은 메시지: {{ messageFromChild }}</p>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  data() {
    return {
      messageFromChild: '',
    };
  },
  methods: {
    handleChildEvent(message) {
      this.messageFromChild = message;
    }
  }
};
</script>

 

자식컴포넌트에서 

this.$emit("이름", 데이터);

 

으로 데이터를 넘기면

 

부모 컴포넌트에서 

<div @이름="자바스크립트 코드"></div>

 

로 받는 방식

 

다음은 한번에 여러개의 데이터를 옮기는 방법이다

 

자식 컴포넌트

<template>
  <div>
    <h2>자식 컴포넌트</h2>
    <button @click="sendMessageToParent">데이터 전송</button>
  </div>
</template>

<script>
export default {
  methods: {
    sendMessageToParent() {
      const data = {
        message: '안녕하세요, 부모님!',
        number: 42
      };
      this.$emit('child-event', data);
    }
  }
};
</script>

 

부모 컴포넌트

<template>
  <div>
    <h1>부모 컴포넌트</h1>
    <ChildComponent @child-event="handleChildEvent" />
    <p>부모 컴포넌트에서 받은 메시지: {{ messageFromChild }}</p>
    <p>부모 컴포넌트에서 받은 숫자: {{ numberFromChild }}</p>
  </div>
</template>

<script>
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent,
  },
  data() {
    return {
      messageFromChild: '',
      numberFromChild: 0,
    };
  },
  methods: {
    handleChildEvent(data) {
      this.messageFromChild = data.message;
      this.numberFromChild = data.number;
    }
  }
};
</script>

'Vue' 카테고리의 다른 글

Vuex로 중앙에서 상태 관리하기  (0) 2024.05.07
Vue 프로젝트 경로의 @  (0) 2024.05.07
Vue 프로젝트 동작 순서  (0) 2024.05.02
Props vs EventBus vs Vuex  (0) 2024.05.02
Vue 객체의 기본 속성 정리  (0) 2024.05.02