Pinia란?

Yeeun_Kim·2024년 5월 20일
0
post-thumbnail

1. Pinia란

  • Vue.js용 Store 라이브러리 및 상태 관리 프레임워크 입니다. 주로 Front-end 웹 어플리케이션 구축을 위해 설계되었으며 선언적 구문을 사용하고 자체 상태 관리 API를 제공합니다.

2. Pinia 예제

Pinia 기본 사용
// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { count: 0 }
  },
  // 다음과 같이 정의할 수도 있음:
  // state: () => ({ count: 0 })
  actions: {
    increment() {
      this.count++
    },
  },
})
component에서 사용하는 예제
<script setup>
import { useCounterStore } from '@/stores/counter'

const counter = useCounterStore()

counter.count++
counter.$patch({ count: counter.count + 1 })
// 또는 actions 사용
counter.increment()
</script>

<template>
  <!-- 스토어에서 직접 상태에 액세스 -->
  <div>현재 카운트: {{ counter.count }}</div>
</template>
Pinia composition api 형식 사용

Composition API란?

옵션을 선언하는 대신 import한 함수를 사용하여 vue 컴포넌트를 작성할 수 있는 API 세트이다.

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

3.Vuex와 비교

1) Composition API

  • Pinia는 Vue3의 Composition API에 코드 작성 방식을 제공

2) Store

  • Vuex는 하나의 Store만 가질 수 있기 때문에 파일들을 namespaced modules를 이용하여 폴더를 구분한 후 성격에 따른 sate와 method를 분리하여 구현해야한다.
  • Pinia는 여러 개의 Store를 가질 수 있기 때문에 namespaced modules을 사용하지 않습니다.
  • Vuex와 비교하여 Pinia는 간결한 구조를 가지지만 namespaced되어 독립된 store 객체를 가질 수 있습니다.

3) Mutation

  • Pinia에서는 비동기적, 동기적 로직 모두 Action에서 수행할 수 있기 때문에 mutation이 없어 불필요한 코드를 줄이고, 간결한 코드를 작성할 수 있습니다.

1개의 댓글

comment-user-thumbnail
2024년 6월 3일

이번 기회에 pinia에 대해 알게 되었네요. 감사합니다.

답글 달기