Composition API는 Vue3에서 새로 추가된 함수 기반의 API로, 컴포넌트 로직을 유연하게 구성할 수 있어 코드 재사용성과 가독성을 높여준다. Vue3 공식 문서에서도 권장되는 방식이다.
기존 Options API는 data, methods, computed 등으로 로직이 분산되어 있었고, 프로젝트 규모가 커질수록 유지보수가 어려웠다. 이를 해결하기 위해 Composition API가 도입되었다.
Composition API는 setup() 함수 안에서 다음과 같은 API를 직접 가져와 사용할 수 있다:
ref(), reactive()로 상태 관리computed()watch()onMounted(), onUnmounted() 등provide(), inject()<template>
<button @click="plus()">숫자: {{ cnt }}</button>
</template>
<script setup>
import { ref, onMounted } from 'vue';
const cnt = ref(0);
const plus = () => { cnt.value++ };
onMounted(() => {
console.log('Mounted!');
});
</script>
➡ Composition API를 사용하면 관련 로직이 setup() 안에 한 곳에 모이기 때문에 유지보수성과 가독성이 높아진다.
<script setup> + Composition API 조합은 tree-shaking에 유리하고, 더 작고 빠른 코드 생성 가능
<template>
<button @click="plus()">숫자: {{ cnt }}</button>
</template>
<script setup>
import { ref, computed } from 'vue';
const cnt = ref(0);
const plus = () => { cnt.value++ };
const double = computed(() => cnt.value * 2);
</script>
<template>
<button @click="plus()">숫자: {{ cnt }}</button>
</template>
<script>
export default {
data() {
return {
cnt: 0,
};
},
methods: {
plus() {
this.cnt++;
},
},
computed: {
double() {
return this.cnt * 2;
},
},
};
</script>
ref() – 단일 값을 반응형으로 만들기const count = ref(0); // 내부적으로 { value: 0 }
count.value++;
📌 템플릿에서는 .value 생략 가능:
<p>{{ count }}</p>
reactive() – 객체 전체를 반응형으로 만들기const state = reactive({ count: 0, name: 'Vue' });
state.count++;
📌 .value 없이 바로 접근 가능
defineProps() – 부모 컴포넌트로부터 props 받기const props = defineProps({ name: String });
defineEmits() – 자식 → 부모 이벤트 전달const emit = defineEmits(['greet']);
emit('greet', `Hello, ${props.name}!`);
provide() / inject() – 조상 → 후손 데이터 전달provide('message', message);
const message = inject('message');