Pinia (상태 관리 라이브러리)
Pinia는 Vue 3의 공식 상태 관리 라이브러리로,
Vuex의 후속으로 설계되었습니다.
Vue 3의 Composition API와 잘 통합되며,
사용하기 간단하고 효율적입니다.
Pinia는 상태 관리에 필요한 기본적인 기능들을 제공하고,
Vue 3와 잘 맞도록 설계되었습니다.
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 설치
Pinia를 사용하려면 먼저 프로젝트에 설치해야 합니다.
npm install pinia
1. Pinia 설정
Pinia를 사용하려면 main.js 또는 main.ts 파일에서 Pinia를 앱에 추가해야 합니다.
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia'; // Pinia import
const app = createApp(App);
app.use(createPinia()); // Pinia 플러그인 사용
app.mount('#app');
2. Pinia Store 만들기
Pinia에서 store는 상태를 관리하는 객체입니다.
store는 defineStore 함수를 사용해 정의할 수 있습니다.
각 store는 상태(state), 계산된 값(getters), 액션(actions)을 가질 수 있습니다.
2.1. 간단한 Store 만들기
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
- defineStore는 첫 번째 인자로 store의 이름을 받습니다.
- state는 반응형 상태를 정의합니다. 상태는 함수로 반환해야 합니다.
- actions는 상태를 수정하는 메서드를 정의합니다.
2.2. 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>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
// counter store 가져오기
const counter = useCounterStore();
</script>
- useCounterStore()를 사용하여 store를 가져옵니다.
- counter.count와 같은 방식으로 state에 접근하고, counter.increment()를 호출하여 actions를 실행할 수 있습니다.
3. Getters 사용하기
getters는 상태를 기반으로 계산된 값을 반환하는 역할을 합니다. Vuex의 computed 속성처럼 작동합니다.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
getters: {
doubledCount: (state) => state.count * 2, // count를 두 배로 반환
},
actions: {
increment() {
this.count++;
},
},
});
이제 doubledCount를 사용하여 count의 두 배 값을 쉽게 구할 수 있습니다.
<!-- src/components/Counter.vue -->
<template>
<div>
<p>Count: {{ counter.count }}</p>
<p>Doubled Count: {{ counter.doubledCount }}</p> <!-- doubledCount 출력 -->
<button @click="counter.increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
const counter = useCounterStore();
</script>
4. Store의 상태 변경 (Actions)
Pinia에서 actions는 상태를 변경하는 메서드입니다.
actions 안에서 this를 사용하여 store의 상태에 접근하고 수정할 수 있습니다.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++; // 상태 변경
},
reset() {
this.count = 0; // 상태 리셋
},
},
});
이러한 actions는 컴포넌트에서 호출하여 상태를 수정할 수 있습니다.
<!-- src/components/Counter.vue -->
<template>
<div>
<p>Count: {{ counter.count }}</p>
<button @click="counter.increment">Increment</button>
<button @click="counter.reset">Reset</button> <!-- reset 호출 -->
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
const counter = useCounterStore();
</script>
5. Pinia의 Persisted State (상태 유지하기)
Pinia는 기본적으로 Vue의 반응형 시스템을 사용하기 때문에 페이지를 새로 고침하면 상태가 초기화됩니다.
만약 상태를 로컬 스토리지에 저장하고 싶다면, 외부 플러그인을 사용할 수 있습니다.
예를 들어, pinia-plugin-persistedstate를 사용하면 상태를 로컬 스토리지에 저장하고 복원할 수 있습니다.
5.1. 플러그인 설치
npm install pinia-plugin-persistedstate
5.2. 플러그인 설정
main.js에서 플러그인을 추가해줍니다.
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';
import piniaPersistedstate from 'pinia-plugin-persistedstate'; // 플러그인 import
const app = createApp(App);
const pinia = createPinia();
pinia.use(piniaPersistedstate); // 플러그인 사용
app.use(pinia);
app.mount('#app');
5.3. store에서 persisted 상태 사용하기
store에서 persist 옵션을 설정해주면 상태가 로컬 스토리지에 저장됩니다.
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
persist: true, // 로컬 스토리지에 저장
actions: {
increment() {
this.count++;
},
},
});
이제 페이지를 새로 고침해도 count 상태가 로컬 스토리지에 저장되어 유지됩니다.
6. Pinia와 Composition API
Pinia는 Composition API와 매우 잘 호환됩니다.
setup() 함수 내에서 store를 사용하면,
상태 관리가 더 직관적이고 효율적입니다.
<template>
<div>
<p>Count: {{ counter.count }}</p>
<button @click="counter.increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '../stores/counter';
const counter = useCounterStore();
</script>
정리
- Pinia는 Vue 3의 상태 관리 라이브러리로, Vuex의 후속입니다.
- defineStore로 store를 정의하고, 이를 useStore()로 가져와 사용할 수 있습니다.
- state는 반응형 데이터를 관리하고, actions는 상태를 변경합니다.
- getters는 상태 기반으로 계산된 값을 반환합니다.
- Pinia는 로컬 스토리지 저장을 지원하여 상태를 유지할 수 있습니다.
Pinia는 Vue 3의 Composition API와 잘 통합되어 있어 사용하기 편리하고 직관적입니다.
여러 상태를 관리하거나 글로벌 상태를 사용하고자 할 때 매우 유용하게 사용될 수 있습니다!
'Vue3, Firebase 프로젝트 - 채팅앱 VSignal' 카테고리의 다른 글
7. Pinia Store에서 ref와 reactive를 사용하는 방법 (0) | 2025.03.30 |
---|---|
6. Vue3 Composition API (0) | 2025.03.30 |
4. Vue Router (<router-link>, <router-view>) (0) | 2025.03.30 |
3. Vue3 기본 문법 (0) | 2025.03.30 |
2. 프레임워크란? (0) | 2025.03.30 |