최근 vue3를 학습하며 <script> 와 <script setup> 의 방식을 각각 사용해 보았다.
개인적으로는 script setup의 방식이 코드의 가독성 측면과 Vue3의 Composition API를 사용하는 취지에 더 적합하다고 생각했기 때문에 <script setup>방식을 더 선호하게 되었는데 아직 익숙치 않다보니 두 방법이 어떻게 다른지에 대해 내용을 비교해보기로 했다.
<script setup>을 사용하지 않는 경우에는 일반적으로 setup() 함수를 사용하여 컴포넌트 로직을 구성할 수 있다. setup() 함수는 Vue 3의 Composition API의 진입점 이라고 할 수 있다.
<template>
<button @click="increment">
Count is: {{ count.value }}, double is: {{ double.value }}
</button>
</template>
<script>
import { ref, computed } from 'vue';
export default {
setup() {
const count = ref(0);
const increment = () => { count.value++ };
const double = computed(() => count.value * 2);
return {
count,
increment,
double
};
}
}
</script>
위 예시와 같이 setup() 함수 내에서 count, increment, double을 선언하고 반환하게되면 반환된 값들은 템플릿에서 사용할 수 있게 된다.
컴포넌트의 props와 emits는 다음과 같이 정의할 수 있다.
<script>
export default {
props: {
title: String
},
emits: ['update'],
setup(props, { emit }) {
// ...
}
}
</script>
위 예시에서 props 옵션은 props의 타입을 정의하고 emits 옵션은 컴포넌트 발생시킬 수 있는 이벤트를 정의한다. 이렇게 정의된 props와 emits는 setup() 함수의 인자로 전달된다.
일반적인 <script> 태그 대신 <script setup>을 사용하면, setup() 함수를 명시적으로 선언하지 않아도 <script setup> 내에서 정의된 모든 const 변수는 자동으로 컴포넌트의 setup() 함수에서 반환된 것처럼 템플릿에서 사용할 수 있게된다.
<template>
<button @click="increment">
Count is: {{ count }}, double is: {{ double }}
</button>
</template>
<script setup>
import { ref, computed } from 'vue';
const count = ref(0);
const increment = () => { count.value++ };
const double = computed(() => count.value * 2);
</script>
위 예시와 같이 <script setup> 내에서 선언한 count, increment, double은 템플릿에서 바로 사용할 수 있게 된다.
<script setup> 방식을 사용 할 시에는 defineProps와 defineEmits 함수를 사용하여 컴포넌트의 props와 emits를 정의한다.
<script setup>
const props = defineProps({
title: String
});
const emits = defineEmits(['update']);
</script>
위 예시에서 defineProps 함수는 props의 타입을 정의하고 defineEmits 함수는 컴포넌트가 발생시킬 수 있는 이벤트를 정의한다.