State management with Nuxt 3 — Course part 10

https://www.youtube.com/watch?v=IkpoAKS1s-k&list=PL8HkCX2C5h0XT3xWYn71TlsAAo0kizmVc&index=10

 

유튜브 강의를 참고하고 있습니다.

 


State Management란

상태 관리(State Management)에서 상태(State)란, 앱 구동에 필요한 기본 데이터 소스이다.

이 상태를 변경시킬 때 사용하는 것이 상태 관리이다. 

쉽게 말해 컴포넌트 간의 데이터 전달이나 데이터 변경을 효율적으로 하는 방법이다.

 


1. 일반 변수

  • pages/index.vue

일반 변수를 선언하듯이 counter 변수를 만들면 클릭 이벤트를 만들어도 화면에는 반영되지 않는다.

콘솔창에서만 counter 변수가 증가, 감소한다.

<script setup lang="ts">
let counter = 0

function increment() {
  counter++
  console.log('증가', counter)
}

function decrease() {
  counter--
  console.log('감소', counter)
}
</script>

<template>
  <section>
    <h2>counter 변수</h2>

    <p>{{ counter }}</p>

    <button @click="increment">+</button>
    <button @click="decrease">-</button>
  </section>
</template>

 

2. useState 변수

  • composables/state.ts

useState에 counter 변수를 만든다.

export const useCounter = () => useState<number>('counter', () => 0)

 

  • pages/index.vue

useState를 통해 변수를 만들면 데이터가 변하는 즉시, 화면에서도 변경된다.

<script setup lang="ts">
import { useCounter } from '@/composables/state';

const stateCounter = useCounter()
</script>

<template>
  <section>
    <h2>useState 변수</h2>

    <p>{{ stateCounter }}</p>

    <button @click="stateCounter++">+</button>
    <button @click="stateCounter--">-</button>
  </section>
</template>

 

3. Pinia store 라이브러리

https://pinia.vuejs.org/

Pinia store에 대한 자세한 설명은 위의 링크를 참고한다.

 

  • stores/counter.ts
  1. 터미널에서 yarn add pinia 또는 npm install pinia 명령어를 입력해 pinia 패키기를 설치한다.
  2. pinia를 import 한다.
  3. useCounterStore를 만들고, state에 초기값을 선언한다.
  4. actions에 이벤트를 만든다.
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },

  actions: {
    increment() {
      this.count++
    },

    decrement() {
      this.count--
    }
  }
})

 

  • pages/index.vue

pinia를 통해 변수를 만들면 데이터가 변하는 즉시, 화면에서도 변경된다.

<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';

const piniaCounter = useCounterStore()
</script>

<template>
  <section>
    <h2>Pinia 변수</h2>

    <p>{{ piniaCounter.counter }}</p>

    <button @click="piniaCounter.increment">+</button>
    <button @click="piniaCounter.decrement">-</button>
  </section>
</template>

 


useState vs Pinia

Nuxt을 사용해 개발을 하기 위해서는 상태 관리를 어떻게 할지 정해야 한다.

간단한 앱에서는 useState를 사용하고, 복잡한 앱에서는 Pinia를 사용한다는 의견이 많다.

 

Pinia는 Vue.js용 스토어 라이브러리 및 상태 관리 프레임워크이다. 

Pinia에서 제공하는 많은 기능들이 있고, 개발자는 그 기능들을 직접 만들 필요가 없다.

DevTools를 통합할 수 있고, getter와 actions 기능을 통해 상태를 변경할 수 있는 구체적인 방법을 정의할 수 있다.

 

따라서 앱의 얼마나 복잡한지 파악한 다음에 어떤 수준의 도구를 선택할지 결정하면 된다.

 

+ Recent posts