✅ Vuex vs Pinia: 개념 및 구조 비교
항목 | Vuex | Pinia |
공식 지원 | Vue 2/3 | ✅ Vue 3에서 공식 채택 |
상태 정의 방식 | 객체 기반 (state, mutations 등) | Composition API 기반 (함수형) |
TypeScript 지원 | 제한적, 다소 번거로움 | ✅ 타입 추론 강력, 사용 매우 편함 |
구조 | 복잡 (mutations + actions + modules) | ✅ 단순 (actions만으로 상태 관리) |
학습 난이도 | 상대적으로 높음 | ✅ 매우 쉬움 |
✅ Pinia 설치 및 설정
🔧 1. 설치
npm install pinia
🔧 2. main.js 설정
// src/main.js
import { createPinia } from 'pinia'; // 피니아 등록
const pinia = createPinia(); // pinia 객체를 가져와 변수에 할당
createApp(App)
.use(pinia) // store 대신 pinia 사용
.mount('#app')
🔧 3. store 폴더 구조 예시
src/
├── store/
│ └── counter.js
├── components/
│ └── Counter.vue
├── main.js
🔧 4. 스토어 예시 (store.js
)
import { defineStore } from "pinia";
// store 만들기 (export를 써서 외부에서 사용 가능하게)
export const useStore = defineStore('main', { // main은 store 이름 -> store 여러 개 정의 가능
state: () => ({
// 상태변수 정의
weatherData: {
temp: 0,
city: 'Seoul',
},
}),
actions: {
// 함수
updateWeather(payload) {
this.weatherData = payload;
this.weatherData.temp = payload.main.temp;
this.weatherData.city = payload.name;
},
toggleButton () {
this.toggle = !this.toggle
},
// 비동기 함수 async/await 문법 써야함
async getWeather() {
const API_KEY = import.meta.env.VITE_API_KEY;
const API_URL = `https://api.openweathermap.org/data/2.5/weather?q=${this.weatherData.city}&appid=${API_KEY}`
await fetch(API_URL)
.then(res => res.json())
.then(data => {
this.updateWeather(data);
})
.catch(err => {
alert('에러가 발생했습니다. 잠시 후 다시 시도해 주세요.');
})
}
}
});
✅ 결론 요약
- Pinia는 Vuex의 복잡한 구조를 대체하는 공식 Vue 3 상태 관리 도구
mutations
제거 → 단순한actions + ref
구조
- Vue 3 + Composition API와 자연스럽게 통합됨
- 설치도 간단하고 Devtools 연동도 훌륭함
Share article