mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

vue

Vue Pinia.

Pinia store, state/getters/actions, 컴포넌트 밖 상태 공유

Pinia는 Vue 공식 전역 상태 라이브러리로, store 단위로 state, getters, actions를 두고 컴포넌트 간 데이터를 공유합니다.

📘 기본 store

Pinia 스토어와 컴포넌트 상태 흐름

// 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

스타일형태
Optionsstate, getters, actions 객체
SetupComposition API 함수 (위 예시)
  • Setup store가 composable과 익숙하고 TypeScript에 유리

⚖️ React와 비교

PiniaReact
공식 패턴Pinia (Vue 3)Context, Zustand, Redux 등
구독storeToRefs로 반응형 유지useSyncExternalStore 등
DevToolsPinia 플러그인Redux/Zustand devtools
  • Vue provide/inject는 트리 범위, Pinia는 앱 전역

🔗 참고 자료

  • Pinia — Vue 공식 상태 관리 라이브러리 문서 홈이다.
  • Introduction — Pinia의 역할과 설치를 설명한다.
  • Core Concepts — store, state, getters, actions를 설명한다.
  • StatestoreToRefs와 state 사용법을 설명한다.