Vue 3 애플리케이션에서는 상태(데이터)를 중앙 집중식으로 관리하기 위해 Pinia를 주로 사용합니다. 이는 Vue 2의 Vuex와 유사한 역할을 하지만, Pinia는 더 간결하고 직관적인 API를 제공하며, TypeScript 지원이 더욱 강화된 것이 특징입니다. 여러 컴포넌트 간에 공유되는 데이터를 Pinia를 통해 중앙에서 관리하고, 특정 컴포넌트 내부에서만 사용되는 데이터는 해당 컴포넌트 내에서 직접 관리하는 것이 일반적인 개발 방식입니다.
1. Pinia 환경 설정 및 초기화
1.1. Pinia 설치
먼저 프로젝트에 Pinia를 추가해야 합니다. 다음 npm 명령어를 사용하여 Pinia 패키지를 설치합니다:
npm i pinia
1.2. Vue 애플리케이션에 Pinia 적용
설치 후, Vue 애플리케이션의 진입점(예: main.ts 또는 main.js)에서 Pinia를 생성하고 애플리케이션에 등록합니다. 이를 통해 모든 컴포넌트에서 Pinia 스토어에 접근할 수 있게 됩니다.
// main.ts
import { createApp } from "vue";
import App from "./App.vue";
import { createPinia } from "pinia"; // Pinia 모듈 임포트
const app = createApp(App);
const piniaInstance = createPinia(); // Pinia 인스턴스 생성
app.use(piniaInstance); // Vue 앱에 Pinia 플러그인 등록
app.mount("#app"); // 애플리케이션을 DOM에 마운트
1.3. 예시 컴포넌트 구성
Pinia의 기능을 설명하기 위해 두 가지 예시 컴포넌트를 가정합니다: CounterComponent.vue와 RandomQuote.vue. 다음은 Pinia를 적용하기 전 RandomQuote.vue 컴포넌트가 로컬 상태를 관리하는 방식의 예시입니다.
<!-- RandomQuote.vue 컴포넌트 (초기 로컬 상태 관리 예시) -->
<script setup lang="ts">
import { reactive } from 'vue';
import axios from 'axios';
import { nanoid } from 'nanoid';
// 명언 데이터의 타입을 정의합니다.
interface Quote {
id: string;
text: string;
}
// 로컬 상태로 명언 목록을 관리합니다.
const quoteList = reactive<Quote[]>([
{ id: nanoid(), text: '인생은 용감한 모험이거나 아무것도 아니다.' },
{ id: nanoid(), text: '성공은 최종적인 것이 아니며, 실패는 치명적이지 않다.' },
{ id: nanoid(), text: '가장 큰 영광은 넘어지지 않는 것이 아니라, 넘어질 때마다 일어서는 것이다.' }
]);
// 외부 API에서 새로운 명언을 가져와 목록에 추가하는 함수
async function fetchNewQuote() {
try {
// API 요청 및 응답에서 content 필드를 quoteText로 비구조화 할당 및 이름 변경
const { data: { content: quoteText } } = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json');
quoteList.unshift({ id: nanoid(), text: quoteText }); // 목록 맨 앞에 추가
} catch (error) {
console.error('명언을 불러오는 중 오류 발생:', error);
}
}
</script>
<template>
<div>
<button @click="fetchNewQuote">새 명언 가져오기</button>
<ul>
<li v-for="quote in quoteList" :key="quote.id">{{ quote.text }}</li>
</ul>
</div>
</template>
2. Pinia 스토어 정의 및 데이터 접근
2.1. 스토어 정의
Pinia 스토어는 defineStore 함수를 사용하여 정의합니다. state 속성은 애플리케이션의 실제 상태를 반환하는 함수여야 합니다.
src/stores/counter.ts 파일에 카운터 스토어를 정의합니다:
// src/stores/counter.ts
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', { // 스토어 이름은 'counter'
// Pinia 스토어의 실제 상태를 정의하는 곳
state: () => ({
currentCount: 0, // 현재 카운트 값
statusMessage: 'Ready' // 스토어 상태 메시지
}),
});
src/stores/quote.ts 파일에 명언 목록 스토어를 정의합니다:
// src/stores/quote.ts
import { defineStore } from 'pinia';
import { nanoid } from 'nanoid'; // ID 생성을 위해 nanoid 임포트
// 명언 아이템의 타입을 정의합니다.
interface QuoteItem {
id: string;
content: string;
}
export const useQuoteStore = defineStore('quote', { // 스토어 이름은 'quote'
state: () => ({
quotes: <QuoteItem[]>[ // 명언 목록 배열
{ id: nanoid(), content: '나는 생각한다. 고로 존재한다.' },
{ id: nanoid(), content: '하늘 아래 새로운 것은 없다.' },
{ id: nanoid(), content: '모든 길은 로마로 통한다.' }
],
}),
});
2.2. 스토어 데이터 읽기
컴포넌트에서 스토어 데이터를 읽으려면 해당 스토어 훅을 호출한 후 반환된 스토어 인스턴스를 사용합니다.
<!-- CounterComponent.vue -->
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
console.log('현재 카운트:', counterStore.currentCount);
console.log('상태 메시지:', counterStore.statusMessage);
// Pinia 스토어의 상태는 Proxy 객체로 래핑되어 있으며,
// Vue의 `reactive` 객체 내부에 `ref` 값이 있을 때처럼,
// 내부 `ref` 값은 `.value` 없이 자동으로 언래핑되어 접근 가능합니다.
// 즉, `counterStore.currentCount`는 이미 언래핑된 값을 반환합니다.
</script>
<template>
<div>
<p>현재 스토어 카운트: {{ counterStore.currentCount }}</p>
</div>
</template>
ref와 reactive 내부 ref의 `.value` 접근 방식 차이는 다음과 같습니다:
import { reactive, ref } from 'vue';
// reactive 객체 내부에 ref가 있는 경우
const exampleObject = reactive({
valueA: 10,
valueB: 'hello',
valueC: ref(30) // ref가 reactive 내부에 포함됨
});
console.log(exampleObject.valueA); // 10 (일반 속성처럼 접근)
console.log(exampleObject.valueC); // 30 (ref가 자동으로 언래핑됨, .value 불필요)
// 독립적인 ref 변수의 경우
const standAloneRef = ref(99);
console.log(standAloneRef.value); // 99 (.value로 접근해야 실제 값을 얻음)
3. 스토어 데이터 수정 방식
Pinia 스토어의 데이터를 수정하는 방법은 주로 세 가지가 있습니다. CounterComponent.vue의 카운트 증가 기능을 예시로 살펴보겠습니다.
3.1. 직접 상태 변경
가장 간단한 방법으로, 스토어 인스턴스의 상태 속성에 직접 값을 할당하여 변경합니다.
// CounterComponent.vue 내부에서
function incrementDirectly(amount: number) {
counterStore.currentCount += amount; // currentCount를 직접 증가
}
3.2. $patch 메서드를 이용한 일괄 변경
여러 상태 속성을 한 번에 효율적으로 변경해야 할 때 $patch 메서드를 사용합니다. 이는 성능 최적화에 도움이 됩니다.
// CounterComponent.vue 내부에서
function updateBatch(amount: number) {
// 객체 형태로 여러 상태를 한 번에 변경
counterStore.$patch({
currentCount: counterStore.currentCount + amount,
statusMessage: `Updated by ${amount} using $patch`
});
// 또는 함수 형태로 전달하여 상태에 접근
// counterStore.$patch(state => {
// state.currentCount += amount;
// state.statusMessage = `Updated by $patch function`;
// });
}
3.3. actions를 통한 복잡한 로직 처리
비동기 작업, 복잡한 비즈니스 로직, 또는 여러 컴포넌트에서 재사용되는 상태 변경 로직이 필요한 경우 actions를 정의하고 사용합니다. this를 통해 스토어의 다른 상태나 getter, 액션에 접근할 수 있습니다.
src/stores/counter.ts 파일에 액션을 추가합니다:
// src/stores/counter.ts (actions 추가)
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
currentCount: 0,
statusMessage: 'Ready'
}),
actions: {
// count 값을 특정량만큼 증가시키는 액션
incrementCount(amount: number) {
this.currentCount += amount;
this.statusMessage = `Increased by ${amount} via action`;
},
// 비동기 작업을 수행하여 초기 카운트 값을 설정하는 액션
async fetchInitialCount() {
this.statusMessage = 'Fetching initial count...';
await new Promise(resolve => setTimeout(resolve, 1000)); // 1초 대기 시뮬레이션
this.currentCount = 100; // 가상의 초기값 설정
this.statusMessage = 'Initial count loaded.';
}
}
});
컴포넌트에서 액션을 호출합니다:
// CounterComponent.vue
function performActionIncrement() {
counterStore.incrementCount(5); // 5만큼 증가시키는 액션 호출
}
// 비동기 액션 호출
counterStore.fetchInitialCount();
4. storeToRefs를 활용한 반응형 비구조화 할당
Pinia 스토어 인스턴스에서 상태 속성들을 직접 비구조화 할당(let { property } = storeInstance)하면 해당 속성들은 반응성을 잃게 됩니다. 즉, 스토어의 상태가 변경되어도 컴포넌트에서는 업데이트되지 않습니다. 이 문제를 해결하기 위해 Pinia는 storeToRefs 헬퍼 함수를 제공합니다.
storeToRefs는 스토어의 state 속성만을 가져와 각각을 반응형 ref로 변환하여 반환합니다. 이를 통해 컴포넌트에서 스토어 상태를 비구조화 할당하면서도 반응성을 유지할 수 있습니다.
<!-- CounterComponent.vue -->
<template>
<div class="counter-display">
<h2>현재 값: {{ countValue }}</h2>
<h3>상태: {{ currentStatus }}</h3>
<!-- Getter 데이터 사용 -->
<p>두 배 값: {{ doubledCount }}</p>
<p>대문자 상태: {{ upperCaseStatus }}</p>
</div>
</template>
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
import { storeToRefs } from 'pinia'; // Pinia 헬퍼 함수 임포트
const counterStore = useCounterStore();
// 경고: 스토어를 직접 비구조화 할당하면 반응성을 잃습니다.
// let { currentCount, statusMessage } = counterStore;
// console.log(currentCount); // 이 값은 스토어 변경 시 업데이트되지 않습니다.
// storeToRefs를 사용하여 스토어의 상태를 반응형 ref로 변환합니다.
// 이렇게 변환된 변수(countValue, currentStatus)는 스토어 상태 변화에 따라 자동으로 업데이트됩니다.
const { currentCount: countValue, statusMessage: currentStatus } = storeToRefs(counterStore);
// 참고: Vue의 toRefs와 Pinia의 storeToRefs의 차이
// Vue의 toRefs는 어떤 reactive 객체든 그 속성들을 ref로 변환하지만, 스토어의 모든 속성(메서드 포함)을 변환하려 합니다.
// console.log("toRefs 결과:", toRefs(counterStore));
// Pinia의 storeToRefs는 Pinia 스토어의 'state' 속성만을 반응형 ref로 효율적으로 변환합니다.
console.log("storeToRefs 결과:", storeToRefs(counterStore));
</script>
5. Getters를 활용한 파생 상태
Pinia의 getters는 스토어의 상태를 기반으로 계산된 값을 제공합니다. 이는 Vue의 computed 속성과 유사하며, 상태가 변경될 때 자동으로 업데이트됩니다. getters는 캐싱되어 있어, 의존하는 상태가 변경되지 않는 한 여러 번 접근해도 계산을 다시 수행하지 않습니다.
src/stores/counter.ts 파일에 getters를 추가합니다:
// src/stores/counter.ts (getters 추가)
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
currentCount: 0,
statusMessage: 'Ready'
}),
getters: {
// 1. state를 인자로 받아 카운트 값의 두 배를 반환하는 getter
doubledCount: (state) => {
return state.currentCount * 2;
},
// 2. `this`를 통해 다른 getter나 state에 접근하는 getter (상태 메시지를 대문자로 변환)
// TypeScript에서는 반환 타입을 명시하는 것이 좋습니다.
upperCaseStatus(): string {
// 여기서 'this'는 현재 Pinia 스토어 인스턴스를 가리킵니다.
return this.statusMessage.toUpperCase();
},
// 현재 카운트가 짝수인지 확인하는 getter
isEven(): boolean {
return this.currentCount % 2 === 0;
}
},
actions: {
// ... 기존 액션
}
});
컴포넌트에서 Getter 데이터를 사용하려면 storeToRefs를 통해 가져옵니다 (위의 storeToRefs 예시 코드에 doubledCount와 upperCaseStatus가 포함되어 있습니다).
6. actions를 이용한 명언 API 연동
이전에 RandomQuote.vue 컴포넌트에서 로컬로 관리하던 명언 API 호출 로직을 Pinia 스토어의 actions로 옮겨 중앙 집중화하고 재사용성을 높일 수 있습니다.
src/stores/quote.ts 파일에 actions를 추가합니다:
// src/stores/quote.ts (actions 추가)
import { defineStore } from 'pinia';
import { nanoid } from 'nanoid';
import axios from 'axios'; // axios 임포트
interface QuoteItem {
id: string;
content: string;
}
export const useQuoteStore = defineStore('quote', {
state: () => ({
quotes: <QuoteItem[]>[
{ id: nanoid(), content: '시작이 반이다.' },
{ id: nanoid(), content: '늦었다고 생각할 때가 가장 빠르다.' },
],
}),
actions: {
// 외부 API에서 새로운 명언을 가져와 스토어에 추가하는 비동기 액션
async addRandomQuote() {
try {
// API 요청 및 응답 데이터 파싱:
// 응답 객체에서 data.content를 quoteText로 비구조화 할당하고 이름을 변경합니다.
const { data: { content: quoteText } } = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json');
// 새로운 명언 객체 생성
const newQuote: QuoteItem = {
id: nanoid(),
content: quoteText
};
// 스토어의 quotes 배열에 추가 (unshift는 배열의 맨 앞에 추가)
this.quotes.unshift(newQuote);
} catch (error) {
console.error('명언을 가져오는 데 실패했습니다:', error);
// 사용자에게 에러를 알리는 등의 추가적인 에러 처리 로직을 여기에 구현할 수 있습니다.
}
},
},
});
이제 RandomQuote.vue 컴포넌트를 수정하여 스토어의 액션을 호출하도록 변경합니다:
<!-- RandomQuote.vue -->
<script setup lang="ts">
import { useQuoteStore } from '@/stores/quote';
import { storeToRefs } from 'pinia';
const quoteStore = useQuoteStore();
// 스토어의 quotes 상태를 반응형 ref로 가져옵니다.
const { quotes: storedQuotes } = storeToRefs(quoteStore);
// 버튼 클릭 시 Pinia 스토어의 액션을 호출합니다.
function fetchAndAddQuote() {
quoteStore.addRandomQuote();
}
</script>
<template>
<div>
<button @click="fetchAndAddQuote">새 명언 추가 (Pinia 사용)</button>
<ul>
<li v-for="quote in storedQuotes" :key="quote.id">{{ quote.content }}</li>
</ul>
</div>
</template>
7. $subscribe를 이용한 스토어 상태 변경 감지
Pinia의 $subscribe 메서드를 사용하면 스토어의 상태 변경을 감지하고, 변경이 발생할 때마다 특정 콜백 함수를 실행할 수 있습니다. 이는 로깅, 분석, 또는 상태를 로컬 스토리지에 저장하여 페이지 새로고침 시에도 데이터를 유지하는 등의 목적으로 유용합니다.
<!-- RandomQuote.vue (또는 App.vue 같은 최상위 컴포넌트) -->
<script setup lang="ts">
import { useQuoteStore } from '@/stores/quote';
import { storeToRefs } from 'pinia';
const quoteStore = useQuoteStore();
const { quotes: storedQuotes } = storeToRefs(quoteStore);
// 스토어의 `quotes` 상태가 변경될 때마다 로컬 스토리지에 저장합니다.
// `$subscribe` 콜백은 변경 정보(mutation)와 변경 후의 스토어 상태(state)를 인자로 받습니다.
quoteStore.$subscribe((mutation, state) => {
console.log('Pinia quoteStore 상태 변경 감지:', mutation.storeId, mutation.type);
console.log('변경 후 상태:', state.quotes);
// 'persisted_quotes' 키로 localStorage에 quotes 배열을 JSON 문자열 형태로 저장
localStorage.setItem('persisted_quotes', JSON.stringify(state.quotes));
}, { detached: true }); // `detached: true`는 컴포넌트가 언마운트되어도 구독을 유지합니다.
// 컴포넌트가 마운트될 때 localStorage에서 기존 데이터를 불러와 스토어 상태를 초기화합니다.
// (일반적으로 스토어 자체의 초기화 로직에 포함하는 것이 더 좋습니다.)
const savedQuotes = localStorage.getItem('persisted_quotes');
if (savedQuotes) {
// Pinia의 $patch를 사용하여 스토어 상태를 초기화합니다.
quoteStore.$patch({ quotes: JSON.parse(savedQuotes) });
}
function fetchAndAddQuote() {
quoteStore.addRandomQuote();
}
</script>
<template>
<div>
<button @click="fetchAndAddQuote">새 명언 추가 (Pinia 사용)</button>
<ul>
<li v-for="quote in storedQuotes" :key="quote.id">{{ quote.content }}</li>
</ul>
</div>
</template>