본문 바로가기

Web/Vue

[Vue] 4-2. Component 자식에서 부모로 데이터전송

 

이전글: [Web/Vue] - [Vue] 4-1. Component 부모에서 자식으로 데이터전송

 

[Vue] 4-1. Component 부모에서 자식으로 데이터전송

https://kr.vuejs.org/v2/guide/components.html 컴포넌트 — Vue.js Vue.js - 프로그레시브 자바스크립트 프레임워크 kr.vuejs.org 컴포넌트 작성 컴포넌트는 부모-자식 관계에서 가장 일반적으로 함께 사용하기..

tjddnjs625.tistory.com

 

Emit : 자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달할 때 사용됩니다.

 

먼저, 상위 클래스에서 컴포넌트를 삽입할 때 v-on:xxx(약어 @xxx)를 사용해 커스텀 이벤트를 만듭니다.

여기서 cChangeName은

자식컴포넌트에서

this.$emit에서 사용할 이벤트 이름이며,

pChangeName은 부모 컴포넌트에 있는 메소드 이름입니다.

왼쪽이 자식 컴포넌트에서 사용할 $emit의 이벤트 이름, 오른쪽은 부모 컴포넌트에서 실행할 메소드라고 생각하면 됩니다.

 

Emit 자식에서 부모로 데이터 전송

1. ParentComponent.vue ( 부모 컴포넌트)

<template>
<child-component name="홍길동" v-on:pChangeName="cChangeName"></child-component>
</template>

<script>
import ChildComponent from "./Component/ChildComponent.vue";

export default {
  name: "ParentComponent",
  components: {
    "child-component": ChildComponent,
  },
  data: function() {
    return {
     name:"",
     age: 0,
    }
  },
  methods:{
    pChangeName: function(name){
      console.log(name);
    }
  }
  ...
}
</script>

 

2. ChildComponent.vue ( 자식 컴포넌트)

<template>
	<div>
    	<p>{{name}}<p>
        <p>{{age}}<p>
        <button type='button' @click="cChangeName">이름변경</button>
    </div>
</template>

<script>
export default {
  name: "ChildComponent",
  props: {
    name:String,
    age: {
    	type:Number,
        default: 20   // 받는 데이터가 없을 경우 default 지정가능
    }
  },
  methods:{
    cChangeName: function(){
      this.$emit("pChangeName","김개똥");
    }
  }
  ...
}
</script>