Vue3, Firebase 프로젝트 - 채팅앱 VSignal

6. Vue3 Composition API

그랜파 개발자 2025. 3. 30. 20:55

Composition API

Composition API는 Vue 3에서 도입된 새로운 방식의 API로,
기존의 Options API보다 더 유연하고 재사용 가능한 코드를 작성할 수 있도록 도와줍니다.
Composition API는 setup() 함수와 함께 사용되며,
컴포넌트의 로직을 명확하게 분리하고,
여러 컴포넌트 간에 재사용할 수 있도록 해줍니다.

 

1. Vue가 뭐야? 
2. 프레임워크란?
3. Vue3 기본 문법
4. Vue Router (<router-link>, <router-view>)
5. Pinia (상태 관리 라이브러리)
6. Vue3 Composition API
7. Pinia Store에서 ref와 reactive를 사용하는 방법
8. Pinia에서의 Composition API 스타일과 Options API 스타일

 

여기서는 Pinia와 Composition API를 함께 사용하여 상태 관리 방법을 설명하겠습니다.

Composition API 개념

Composition API는 setup() 함수를 중심으로 작동합니다.
setup() 함수는 컴포넌트가 생성될 때 호출되며,
이 함수 내에서 반응형 데이터(reactive), 계산된 값(computed), 라이프 사이클 훅 등을 설정합니다.

  • reactive(): 반응형 객체를 만듭니다.
  • ref(): 단일 값을 반응형으로 만듭니다.
  • computed(): 계산된 값을 만듭니다.
  • watch(): 반응형 값의 변화를 감지합니다.

1. Pinia와 Composition API 사용하기

Pinia는 Composition API와 잘 호환되며,
setup() 함수 내에서 Pinia의 store를 사용할 수 있습니다.

1.1. Pinia Store 만들기

우선, Pinia store를 Composition API 스타일로 만들겠습니다.
예를 들어, 카운터를 관리하는 store를 만들어보겠습니다.

// src/stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
    reset() {
      this.count = 0;
    },
  },
});
  • defineStore는 Pinia store를 정의하는 함수입니다.
  • state는 count 값을 저장합니다.
  • actions는 count 값을 증가, 감소, 초기화하는 메서드를 포함합니다.

1.2. Pinia Store 사용하기

컴포넌트에서 Pinia store를 사용하려면
setup() 함수 내에서 Pinia store를 가져와 사용할 수 있습니다.
여기서는 useCounterStore()를 사용하여 상태를 관리합니다.

<!-- src/components/Counter.vue -->
<template>
  <div>
    <p>Count: {{ counter.count }}</p>
    <button @click="counter.increment">Increment</button>
    <button @click="counter.decrement">Decrement</button>
    <button @click="counter.reset">Reset</button>
  </div>
</template>

<script setup>
import { useCounterStore } from '../stores/counter';  // Pinia store import

// Pinia store 가져오기
const counter = useCounterStore();
</script>
  • useCounterStore()를 사용해 store를 가져옵니다.
  • counter.count를 사용하여 반응형 상태에 접근하고, counter.increment(), counter.decrement(), counter.reset()으로 상태를 변경합니다.

2. reactive와 ref 사용하기

Composition API에서 반응형 상태를 만들 때,
reactive ref를 사용할 수 있습니다.

  • reactive() 는 객체나 배열과 같은 복잡한 상태를 반응형으로 만들 때 사용합니다.
  • ref() 는 단일 값(문자열, 숫자 등)을 반응형으로 만들 때 사용합니다.

2.1. reactive() 사용하기

reactive()는 객체를 반응형으로 만듭니다.

// src/components/ReactiveExample.vue
<template>
  <div>
    <p>{{ user.name }} - {{ user.age }}</p>
    <button @click="incrementAge">Increment Age</button>
  </div>
</template>

<script setup>
import { reactive } from 'vue';

const user = reactive({
  name: 'John Doe',
  age: 30,
});

const incrementAge = () => {
  user.age++;
};
</script>
  • reactive()를 사용해 user 객체를 반응형 상태로 만들었습니다.
  • user.name과 user.age에 접근하여 UI를 업데이트할 수 있습니다.

2.2. ref() 사용하기

ref()는 기본형 값(문자열, 숫자 등)을 반응형으로 만듭니다.

// src/components/RefExample.vue
<template>
  <div>
    <p>Counter: {{ counter }}</p>
    <button @click="incrementCounter">Increment</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const counter = ref(0);  // ref로 기본형 값을 반응형으로 만듦

const incrementCounter = () => {
  counter.value++;
};
</script>
  • ref()를 사용해 counter를 반응형으로 만들었습니다.
  • counter.value로 값에 접근하고, counter.value++로 값을 변경할 수 있습니다.

3. computed()와 watch() 사용하기

computed()와 watch()는 Composition API에서 계산된 값과 상태 변화를 감지하는 데 사용됩니다.

3.1. computed() 사용하기

computed()는 계산된 값을 반환합니다.
예를 들어, count 값을 두 배로 계산하는 doubledCount를 만들 수 있습니다.

// src/components/ComputedExample.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled Count: {{ doubledCount }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};

// computed()를 사용하여 count를 두 배로 계산
const doubledCount = computed(() => count.value * 2);
</script>
  • computed()를 사용하여 doubledCount를 계산된 값으로 만들었습니다.
  • doubledCount는 count가 변경될 때마다 자동으로 업데이트됩니다.

3.2. watch() 사용하기

watch()는 반응형 값이 변할 때 특정 작업을 수행할 수 있게 해줍니다.

// src/components/WatchExample.vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};

// watch()로 count 값 변화 감지
watch(count, (newCount, oldCount) => {
  console.log(`Count changed from ${oldCount} to ${newCount}`);
});
</script>
  • watch()를 사용하여 count 값이 변경될 때마다 콘솔에 새로운 값과 이전 값을 출력합니다.
  • watch()는 상태 변화를 감지하고, 그에 맞는 작업을 실행할 때 유용합니다.

정리

  • setup() 함수는 Composition API의 핵심이며, 컴포넌트 로직을 분리하고 재사용할 수 있게 도와줍니다.
  • reactive() 는 객체를, ref() 는 기본형 값을 반응형으로 만듭니다.
  • computed() 는 계산된 값을 반환하고, watch() 는 상태 변화를 감지하여 특정 작업을 실행할 수 있습니다.
  • Pinia는 Composition API와 잘 호환되며, defineStore로 상태를 관리하고, useStore()로 상태를 가져와 사용할 수 있습니다.

Composition API와 Pinia를 사용하면 더 간결하고 유지보수하기 쉬운 코드를 작성할 수 있습니다.

 

이전 : 5. Pinia (상태 관리 라이브러리)

다음 : 7. Pinia Store에서 ref와 reactive를 사용하는 방법