부모컴포넌트에서 자식컴포넌트로 데이터를 전달하는 예제

테스트(실제 입력 화면)


예제

1.아래의 예제는 v-model을 사용한 양방향 예제를 사용하지 않았다

2.자식요소에서 ref가 아닌 toRefs를 사용하였다

3.데이터 흐름은 아래의 예제의 1~ 6이다


ParentComponent.vue (부모 요소)

<template>
  <div>
    <ChildComponent :parentData="message" @updateData="updateMessage" /> // 2
    <div> 입력한값 : {{message}}</div>
  </div>
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  setup() {
    const message = ref('초기 메시지'); // 1

    const updateMessage = (newMessage) => {
      message.value = newMessage; // 6
    };

    return { message, updateMessage };
  }
};
</script>


ChildComponent.vue (자식 요소)

<template>
  <div>
    <input :value="parentData" @input="onInput" /> // 4
  </div>
</template>

<script>
import { defineComponent, toRefs,ref } from 'vue';

export default defineComponent({
  props: {
    parentData: String
  },
  setup(props, { emit }) {
    // ★ props의 값을 그대로 사용하면 반응성이 유지되지만, 여기서는 props의 값을 재할당하는 해주는 과정을 거치게 되므로 반응성이 사라지게 된다. 
    //그래서 toRefs()를 사용한 것이다
    const { parentData } = toRefs(props); // 3       // props로 받은 객체의 모든 값을 ref로 변경하는 경우
    // const parentData = toRef(props, 'parentData') // props로 받은 객체의 모든 값을 ref로 변경하는것이 아닌 하나의 값만 변경하는 경우
    const onInput = (event) => {
      emit('updateData', event.target.value); // 5
    };

    return { parentData, onInput };
  }
});
</script>



toRefs를 자식 컴포넌트에서 사용한 이유

setup 함수의 첫 번째 인자는 props입니다. setup 함수 내부의 props는 반응형이며, 새 props가 전달되면 업데이트됩니다.

export default {
  props: {
    title: String
  },
  setup(props) {
    console.log(props.title)
  }
}

props 객체를 분해할 경우, 분해 된 변수는 반응성을 잃게 됩니다. 따라서 항상 props.xxx처럼 접근하는 것이 좋습니다.

Props를 분해해야 하거나, 반응성을 유지하면서 외부 함수(부모)에 props를 전달해야 하는 경우, toRefs() 또는 toRef() 유틸리티 API를 사용하여 구현할 수 있습니다.


// 위의 예제에서 toRefs()를 사용한 이유가 여기에 있다

// 부모와 자식간에 데이터 전달에서 전달받은 객체(props)의 반응성을 잃지 않기위해 , 부모에게서 받은 props객체를 반응형 객체 ref로 변경할 필요가있다




참조

Props에서 toRefs를 사용하는 이유

Feb 4, 2024 Views 179