Vue Composition API

정현승·2025년 1월 9일

Composition API

Vue Composition API는 Vue 3에서 새롭게 도입된 API로, 기존의 Options API를 보완하거나 대체할 수 있는 기능을 제공합니다.
주로 코드의 재사용성과 가독성을 높이고 더 유연한 상태 관리 및 로직 구성을 가능하게 합니다.

<script setup>
import { computed } from "vue";
import Child from "./components/Child.vue";

const count = ref(0);
const arr = reactive([1,2,3])
const double = computed(() => count.value * 2);
const increment = () => count.value++;

provide("provideC", count);

watch(count, () => {
  console.log("state2 changed");
});
</script>
<template>
  <h1>{{ count }}</h1>
  <h2>{{ double }}</h2>
  <button @click="increment">증가</button>
  <Child :count="count"/>
</template>
<style scoped></style>
<script setup>
import { inject, onMounted } from "vue";

const props = defineProps({
    count:Number
})

const provideC = inject("provideC")
onMounted(() => {});
</script>
<template>
   <h1>life</h1>
   <p>{{ props.count }}</p>
   <p>pc {{ provideC }}</p>
</template>
<style scoped></style>
  • setup : Composition API를 더욱 간편하게 사용할 수 있도록 제공되는 컴파일 타임 전용 문법입니다.
  • ref와 reactive : ref는 기본자료형, reactive는 참조 자료형의 값에 대한 반응성을 제공합니다.
  • computed : 계산된 값을 정의할 때 사용합니다.
  • watch : 특정 상태를 감시하여 그 상태가 변할 때 추가적인 동작을 수행합니다
  • defineProps : defineProps를 사용하면 컴포넌트의 props를 선언하고 사용할 수 있습니다.
  • defineEmits : defineEmits를 사용하여 컴포넌트에서 이벤트를 선언합니다.
  • provide, inject : 부모-자식 관계(또는 더 깊은 하위 관계)에서 데이터를 공유하기 위해 사용합니다.
  • 라이프사이클 : onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted

0개의 댓글