728x90
1. 기본적인 차이점
<script> | <script setup> | |
작성 방식 | setup() 함수 내에서 Composition API 사용 | setup() 없이 Composition API를 직접 사용 |
템플릿 접근 | return {}을 통해 템플릿에 노출 | 자동으로 템플릿에서 사용 가능 |
컴파일 최적화 | 수동으로 처리 필요 | 더 빠르게 컴파일되고 최적화됨 |
코드 길이 | 더 길고 boilerplate 코드 필요 | 더 짧고 간결함 |
2. 예제 비교
(1) 기존 <script> 방식
<script>
import { ref, computed } from "vue";
export default {
setup() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
return { count, doubleCount };
},
};
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="count++">증가</button>
</div>
</template>
- setup() 내부에서 변수를 선언하고 return을 사용해야 템플릿에서 사용할 수 있음.
- 코드가 다소 길어지고 boilerplate가 많음.
<script setup> 방식
<script setup>
import { ref, computed } from "vue";
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
</script>
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="count++">증가</button>
</div>
</template>
- setup() 함수 없이 바로 변수 선언이 가능함.
- return이 필요 없으며 선언된 변수들이 자동으로 템플릿에서 접근 가능.
- 코드가 짧아지고 가독성이 증가함.
3. 추가적인 차이점
(1) Props 사용
- 기존 <script> 방식
<script>
export default {
props: {
title: String,
},
};
</script>
<template>
<h1>{{ title }}</h1>
</template>
- <script setup> 방식
<script setup>
defineProps<{ title: string }>();
</script>
<template>
<h1>{{ title }}</h1>
</template>
- <script setup>에서는 defineProps()를 사용하여 직접 props를 정의.
(2) Emit 이벤트
- 기존 <script> 방식
<script>
export default {
setup(_, { emit }) {
const sendEvent = () => {
emit("custom-event", "데이터");
};
return { sendEvent };
},
};
</script>
<template>
<button @click="sendEvent">이벤트 발생</button>
</template>
- <script setup> 방식
<script setup>
const emit = defineEmits(["custom-event"]);
const sendEvent = () => {
emit("custom-event", "데이터");
};
</script>
<template>
<button @click="sendEvent">이벤트 발생</button>
</template>
- <script setup>에서는 defineEmits()를 사용하여 더 간결하게 이벤트를 정의 가능.
(3) 컴포넌트 가져오기
- 기존 <script> 방식
<script>
import ChildComponent from "./ChildComponent.vue";
export default {
components: {
ChildComponent,
},
};
</script>
<template>
<ChildComponent />
</template>
- <script setup> 방식
<script setup>
import ChildComponent from "./ChildComponent.vue";
</script>
<template>
<ChildComponent />
</template>
- <script setup>에서는 components 옵션 없이 자동으로 템플릿에서 사용 가능.
4. 어떤 것을 사용해야 할까?
권장 사항:
- <script setup> 사용 → Nuxt 3에서는 더 빠르고 간결하며 최적화가 뛰어남.
- 기존 <script> 방식이 필요한 경우
- defineExpose()를 사용해야 하는 경우
- async setup()을 활용하는 경우
사용해야 하는 경우
상황 | <script> | <script setup> |
코드가 짧고 간결해야 함 | ❌ | ✅ |
템플릿에서 변수 바로 사용 | ❌ return {} 필요 | ✅ 자동으로 접근 가능 |
Composition API 사용 | 가능 | 가능 (더 간편) |
Options API 사용 | 가능 | ❌ (지원 안 됨) |
Vue 플러그인에서 setup 필요 | ✅ | ✅ |
728x90
'Javascript > NuxtJS' 카테고리의 다른 글
[Nuxt3] definePageMeta (0) | 2025.03.09 |
---|---|
[Nuxt3] 중첩 라우팅 (0) | 2025.03.09 |
[Nuxt3] 컨테이너 배포 환경에서 메뉴 동적으로 관리하기 (0) | 2025.03.08 |
[Nuxt3] TypeScript 설정 (0) | 2025.03.08 |
[Nuxt 3] Vuetify 3 SSR 오류 해결하기 (0) | 2025.03.08 |