vue
Vue Pinia.
Pinia store, state/getters/actions, 컴포넌트 밖 상태 공유
Pinia는 Vue 공식 전역 상태 라이브러리로, store 단위로 state, getters, actions를 두고 컴포넌트 간 데이터를 공유합니다.
📘 기본 store
// stores/counter.ts
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(0);
const double = computed(() => count.value * 2);
function increment() {
count.value += 1;
}
return { count, double, increment };
});
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
import { storeToRefs } from 'pinia';
const store = useCounterStore();
const { count } = storeToRefs(store);
</script>
🔀 Options vs Setup store
| 스타일 | 형태 |
|---|---|
| Options | state, getters, actions 객체 |
| Setup | Composition API 함수 (위 예시) |
- Setup store가 composable과 익숙하고 TypeScript에 유리
⚖️ React와 비교
| Pinia | React | |
|---|---|---|
| 공식 패턴 | Pinia (Vue 3) | Context, Zustand, Redux 등 |
| 구독 | storeToRefs로 반응형 유지 | useSyncExternalStore 등 |
| DevTools | Pinia 플러그인 | Redux/Zustand devtools |
- Vue provide/inject는 트리 범위, Pinia는 앱 전역
🔗 참고 자료
- Pinia — Vue 공식 상태 관리 라이브러리 문서 홈이다.
- Introduction — Pinia의 역할과 설치를 설명한다.
- Core Concepts — store, state, getters, actions를 설명한다.
- State —
storeToRefs와 state 사용법을 설명한다.
