[Vue] 상위 컴포턴트와 하위 컴포넌트 간의 데이터 전달

2022. 4. 21. 16:16Vue.JS

 

1. 상위 컴포넌트 → 하위 컴포넌트

input box에 입력한 글을 출력함.

  • 상위 컴포넌트에서 props를 이용해 하위 컴포넌트로 데이터를 보내고 / 하위 컴포넌트에서 v-bind로 데이터를 받는다.
  • App.vue (상위 컴포넌트)
<template>
  <div style="width : 30% display:flex; flex-direction:column;">
    <input type="text" v-model="text">
    <getData v-bind:values="text"></getData>
  </div>
</template>

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

export default {
  data: function() {
    return {
      text:"",
      sendItem:""
    }
  },
  methods:{
    inputSend:function(send){
      return this.sendItem=send
    }
  },
  components: {
    getData,
  },
  comments:{
    'getData':getData,
  }
}
</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>
  • getData.vue (하위 컴포넌트)
<template>
    <div style="margin-top:20px">
        <span>
            부모 컨포넌트 내용 : {{values}}
        </span>
    </div>
</template>

<script>

export default {
    props:['values'],
}

</script>

<style scoped>
</style>

 

 


 

2. 하위 컴포넌트 → 상위 컴포넌트

  • 하위 컴포넌트에서 $emit을 이용해 상위 컴포넌트로 데이터를 보내고 / 상위 컴포넌트에서는 v-one로 데이터를 받는다.
  • sendData.vue (하위 컴포넌트)
<template>
    <div style="margin-top:20px">
        <input type="text" v-model="childValue">
        <button  style="margin-left:10px" v-on:click="sendValue">자식 컴포턴트 내용 보내기</button>
    </div>
</template>

<script>

export default {
    data:function(){
        return{
            childValue:""
        } 
    },

    methods:{
        sendValue:function(){
            this.$emit("text",this.childValue);
            this.childValue="";
        }
    }

}
</script>
  • App.vue (상위 컴포넌트)
<template>
  <div style="width : 30% display:flex; flex-direction:column;">
    <sendData v-on:text="inputSend"></sendData>
    <p>자식 컴포넌트 내용 : {{sendItem}}</p>
  </div>
</template>

<script>
import sendData from './components/sendData.vue'
export default {
  data: function() {
    return {
      text:"",
      sendItem:""
    }
  },
  methods:{
    inputSend:function(send){
      return this.sendItem=send
    }
  },
  components: {
    sendData,
  },
  comments:{
    'sendData':sendData,
  }
}
</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>