DefineProps
Vue 3 setup Composition 으로 넘어오면서 Vue 2의 props 는 DefineProps
로 변경되었다.
기본 형태
// Sample.vue
<script setup>
defineProps({
title: {
Type: String,
required: true
},
order: Number,
category: String
});
</script>
위와 같은 형태로 사용할 수 있다.
저렇게 지정하고 나면 Parent Component에서 값을 넣어줄 수 있다.
// Sample_Parent.vue
<template>
...
<Sample title="Sample Title" order=10 />
...
</template>
defineProps에서 지정된 변수는 template에서 중괄호를 사용하여 값을 사용할 수 있다.
// Sample.vue
<template>
...
<h1> </h1>
<h2> </h1>
...
</template>
다른 한 편, Script 부분에서도 사용할 수 있다.
Parent에서 Child로 값을 넘겨 axios body나 function 변수 값으로 넣고 싶었은데 이 활용법을 몰라서 많이 헤메였던 기억이 있다.
defineProps를 하나의 변수로 받은 다음 vue의 toRefs 함수로 변환하면 script에서 각 값을 사용할 수 있다. toRefs라는 변수명답게 각 변수는 ref 변수이다.
// Sample.vue
<script>
const props = defineProps({
title: {
Type: String,
required: true
},
order: Number,
category: String
});
const { title, order, category } = toRefs(props);
</script>
Written on July 30, 2022