Pinia는 Vue의 공식 상태 관리 라이브러리로, Vuex의 대체제로 등장하였다. 기존 Vuex보다 간결한 API를 제공하며, 자동 타입 추론 기능을 지원한다. Nuxt 3에서는 @pinia/nuxt 모듈을 사용하여 Pinia를 간편하게 통합할 수 있다.
다음 명령어를 실행하여 Pinia를 설치한다.
npm install pinia @pinia/nuxt
설치 과정에서 _ERESOLVE unable to resolve dependency tree_ 오류가 발생할 경우, package.json 파일에 다음 내용을 추가하면 해결할 수 있다.
// path: ./package.json
"overrides": {
"vue": "latest"
}
Nuxt에서 Pinia를 사용하기 위해 nuxt.config.ts 파일에 모듈을 등록해야 한다.
// nuxt.config.ts
export default defineNuxtConfig({
modules: [
"@pinia/nuxt",
],
});
이제 Pinia를 Nuxt 애플리케이션에서 사용할 수 있다.
Pinia에서는 상태(state), 계산된 값(getters), 액션(actions)을 정의하여 사용할 수 있다. 다음은 기본적인 state 값을 가지는 스토어의 예제이다.
// path: ./stores/counter.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => ({
count: 1,
}),
});
📌 설명
- defineStore("counter", {...}) → "counter"는 스토어의 고유한 이름이다.
- state: () => ({ count: 1 }) → count라는 상태 변수를 선언하였다.
Nuxt 3의 컴포넌트에서 Pinia의 상태를 가져와 UI에 적용할 수 있다.
<script setup>
const counterStore = useCounterStore();
</script>
<template>
<h1>카운트 값: {{ counterStore.count }}</h1>
</template>
📌 설명
- useCounterStore()를 통해 스토어를 가져와 count 값을 사용할 수 있다.
- counterStore.count를 {{ }}로 출력하면 초기값인 1이 화면에 나타난다.
Pinia에서는 actions를 이용해 상태 값을 변경할 수 있다.
// path: ./stores/counter.ts
export const useCounterStore = defineStore("counter", {
state: () => ({
count: 1,
}),
actions: {
increment() {
this.count++;
},
},
});
<script setup>
const counterStore = useCounterStore();
</script>
<template>
<h1>카운트 값: {{ counterStore.count }}</h1>
<button @click="counterStore.increment">+</button>
</template>
📌 설명
- increment() 함수가 count 값을 증가시키도록 정의되었다.
- 버튼을 클릭하면 increment()가 실행되어 화면의 count 값이 증가한다.
getters는 computed 속성과 유사한 개념으로, 기존의 state 값을 가공하여 새로운 값을 만들 때 유용하다.
// path: ./stores/counter.ts
export const useCounterStore = defineStore("counter", {
state: () => ({
count: 1,
}),
getters: {
doubleCount: (state) => state.count * 2,
},
});
<script setup>
const counterStore = useCounterStore();
</script>
<template>
<h1>카운트 값: {{ counterStore.count }}</h1>
<h2>두 배 값: {{ counterStore.doubleCount }}</h2>
<button @click="counterStore.increment">+</button>
</template>
📌 설명
- doubleCount는 count 값의 두 배를 계산하는 getter이다.
- doubleCount 값은 반응성을 가지므로 count 값이 변경될 경우 자동으로 업데이트된다.
옵션 | 설명 |
---|---|
state | 컴포넌트에서 사용할 상태 값을 정의한다. |
actions | 상태 값을 변경하는 함수 정의 (비동기 처리 가능) |
getters | 계산된 값을 반환하는 속성 (반응형 유지) |
✅ 타입스크립트 친화적 (자동 타입 추론 지원)
✅ 플러그인 없이 SSR(서버 사이드 렌더링) 지원