Vue

[vue] 부모 - 자식 컴포넌트 데이터 이동

ITtraveler 2024. 8. 1. 11:06

 

 

vue - 부모 자식 컴포넌트 데이터 이동

 

 

 

 

 

app.vue

<template>
  <ParentComponent></ParentComponent>
</template>

<script>
import ParentComponent from './components/ParentComponent.vue'

export default {
  name: 'App',
  components: {
    ParentComponent
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

 

ParentsComponent.vue

<template>
    <h1>부모 컴포넌트</h1>
    {{ messageFromChild }} <!-- 2-6. 받은 메시지 노출 -->
    <hr />
    <!-- 1-2.data()에 작성한 메시지 참조 abcname으로 넘김 -->
    <!-- 2-4. 받아올 emit의 변수명에 get으로 가져오기-->
    <ChildComponent :abcname="messageToChild" @NoThanks="get"/> 
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
    name: "ParentsComponent",
    data() {
        return {
            messageFromChild: "", //2-3.응답받을 변수 생성
            messageToChild: "우리집은 돈이 없다"} //1-1.보낼 메시지 작성
    },
    components: {
        ChildComponent,
    },
    methods: {
        get(e) {
            this.messageFromChild = e; //2-5. 받아온 메시지 변수에 저장
        }
    }
}
</script>

 

 

 

 

ChildComponent.vue

<template>
    <h2>자식 컴포넌트</h2>
    어머님 말씀 : {{ abcname }} <!-- 1-4.가져온 변수 호출 -->
    <button @click="$emit('NoThanks', '알아서 살아볼게요')">답장</button> <!-- 2-2. 전달할변수와 message 작성 -->
</template>
<script>
export default {
    //emit 하위 컴포넌트에서 상위 컴포넌트로 이벤트를 전달하는 방법
    //props: 부모 컴포넌트가 자식 컴포넌트에 데이터를 전달하는 방법
    name: "ChildComponent",
    emit: ["NoThanks"], //2-1. 전달할 변수 생성
    props: ["abcname"] //1-3.parent에서 가져오기
}
</script>