nuxt3 Pinia 적용하기

Nuxt 3에서 Pinia 사용하기

1. Pinia란?

Pinia는 Vue의 공식 상태 관리 라이브러리로, Vuex의 대체제로 등장하였다. 기존 Vuex보다 간결한 API를 제공하며, 자동 타입 추론 기능을 지원한다. Nuxt 3에서는 @pinia/nuxt 모듈을 사용하여 Pinia를 간편하게 통합할 수 있다.

2. Pinia 설치

다음 명령어를 실행하여 Pinia를 설치한다.

npm install pinia @pinia/nuxt

설치 과정에서 _ERESOLVE unable to resolve dependency tree_ 오류가 발생할 경우, package.json 파일에 다음 내용을 추가하면 해결할 수 있다.

// path: ./package.json
"overrides": {
  "vue": "latest"
}

3. Nuxt 설정 파일에 Pinia 추가

Nuxt에서 Pinia를 사용하기 위해 nuxt.config.ts 파일에 모듈을 등록해야 한다.

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    "@pinia/nuxt",
  ],
});

이제 Pinia를 Nuxt 애플리케이션에서 사용할 수 있다.


4. Pinia Store 생성

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에서는 defineStore가 자동으로 임포트되므로 import { defineStore } from "pinia";를 생략할 수 있다.

5. Pinia Store를 활용하여 상태 값 가져오기

Nuxt 3의 컴포넌트에서 Pinia의 상태를 가져와 UI에 적용할 수 있다.

✅ 기본적인 사용법

<script setup>
const counterStore = useCounterStore();
</script>

<template>
  <h1>카운트 값: {{ counterStore.count }}</h1>
</template>

📌 설명

  • useCounterStore()를 통해 스토어를 가져와 count 값을 사용할 수 있다.
  • counterStore.count{{ }}로 출력하면 초기값인 1이 화면에 나타난다.

6. 상태 값 변경 (Actions 활용)

Pinia에서는 actions를 이용해 상태 값을 변경할 수 있다.

increment() 액션 추가

// 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 값이 증가한다.

7. getters를 활용한 계산된 값 사용

getterscomputed 속성과 유사한 개념으로, 기존의 state 값을 가공하여 새로운 값을 만들 때 유용하다.

doubleCount 계산된 값 추가

// path: ./stores/counter.ts

export const useCounterStore = defineStore("counter", {
  state: () => ({
    count: 1,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
});

doubleCount 값을 UI에서 활용

<script setup>
const counterStore = useCounterStore();
</script>

<template>
  <h1>카운트 값: {{ counterStore.count }}</h1>
  <h2>두 배 값: {{ counterStore.doubleCount }}</h2>
  <button @click="counterStore.increment">+</button>
</template>

📌 설명

  • doubleCountcount 값의 두 배를 계산하는 getter이다.
  • doubleCount 값은 반응성을 가지므로 count 값이 변경될 경우 자동으로 업데이트된다.

8. Pinia의 defineStore() 옵션 정리

옵션설명
state컴포넌트에서 사용할 상태 값을 정의한다.
actions상태 값을 변경하는 함수 정의 (비동기 처리 가능)
getters계산된 값을 반환하는 속성 (반응형 유지)

Pinia Info

✅ 타입스크립트 친화적 (자동 타입 추론 지원)
✅ 플러그인 없이 SSR(서버 사이드 렌더링) 지원