[Vue3] Composition API를 defineProps 및 toRefs 함수와 함께 사용하여 반응 속성을 정의
구조분해 사용하기
1. props 이해하기
상위 구성 요소(부모 컴포넌트)에서 하위 구성 요소(자식 컴포넌트)로 데이터를 전달하는 방법이다.
부모 구성 요소에서 속성을 정의하고 해당 값을 사용할 자식 구성 요소에 전달할 수 있다.
하위 구성 요소에서 전달 받을 데이터에 속성을 정의하고 예상 유형(type), 기본값(default), 필수 여부(required)를 지정한다. 그러면 부모 구성 요소는 템플릿에서 자식 구성 요소를 사용할 때 이러한 소품에 데이터를 바인딩할 수 있다.
1-1. 자식 컴포넌트(ChidComponent.vue)
이 예제에서는 message와 count라는 두 개의 props를 예상하는 자식 구성요소가 있다. message 소품은 String 유형이며 필수이다. 즉, 부모 구성 요소에서 제공해야 한다. count 소품은 Number 유형이며 기본값은 0이므로 선택 사항이다.
<script setup>
import {ref, toRefs} from 'vue'
import {defineProps} from 'vue'
const props = defineProps({
message: {
type: String,
required: true,
},
count: {
type: Number,
default: 0,
},
})
//this 키워드로 엑세스
console.log(this.message); // Logs the value of the message prop
console.log(this.count); // Logs the value of the count prop
</script>
<template>
<div>
<h2>{{ message }}</h2>
<p>{{ count }}</p>
</div>
</template>
1-2. 부모 컴포넌트(ParentComponent.vue)
상위 구성 요소의 템플릿에서 하위 구성 요소를 사용하고 message 및 count props에 대한 값을 제공할 수 있다.
message prop은 문자열로 직접 제공되는 반면 count prop은 v-bind 지시문(또는 속기 :)을 사용하여 JavaScript 표현식에 바인딩한다.
그러면 자식 구성 요소는 this 키워드를 사용하여 props의 값에 액세스할 수 있다.
<script seup>
import ChildComponent from './ChildComponent.vue';
</script>
<template>
<div>
<ChildComponent message="Hello from parent" :count="42" />
</div>
</template>
※ 여기서 this로 접근하지 않고 구조 분해를 사용해서 편리하게 사용해보자.
2. 구조분해를 사용하여 props 개체에서 반응속성 정의 예제
구조분해를 사용하고 toRefs를 사용하여 props 개체에서 해체되어 반응 참조를 생성한다.
import { defineProps, toRefs } from 'vue';
// Define props
const props = defineProps({
modelValue: {
type: Object,
required: true,
default: default: function () {
return {
acquisitionDate: '',
title: '',
location: ''
}
}
},
isReadOnly: {
type: Boolean,
required: false,
default: false
}
});
// Destructure the modelValue property from props
const { modelValue, isReadOnly } = toRefs(props);
// Access the value
console.log(modelValue.value); // Access the value of modelValue
console.log(isReadOnly.value); // Access the value of isReadOnly