본문 바로가기
개발/VUE

Vue - pinia 간단 세팅 방법

반응형

이번 포스팅에서는 vue3에서 상태관리를 위한 pinia 세팅을 해보겠습니다.

 

pinia, pinia-plugin-persist 설치

pinia : 상태관리 라이브러리

참고링크 : https://pinia.vuejs.kr/core-concepts/

pinia-plugin-persist : storage 저장 plugin

참고링크 : https://seb-l.github.io/pinia-plugin-persist/#nuxt

npm i pinia
npm i pinia-plugin-persist

 

mian.js 에 아래와 같이 pinia, pinia-plugin-persist 사용설정

//pinia 상태관리 plugin
import { createPinia } from 'pinia';
//pinia storage 저장 plugin
import piniaPersist from 'pinia-plugin-persist';

const app = createApp(App);

const pinia = createPinia();
pinia.use(piniaPersist);

app.use(pinia);

 

사용법

- store 생성
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', 
  {
    state : ()=>({
      count : 0
    }),
    getters:{
      doubleCount(){
        return this.count * 2
      }
    },
    actions:{
      increment() {
        this.count++
      }
    },
    persist: {
      enabled: true, //storage 저장유무
      strategies: [
        {
          key: 'counter', //storage key값 설정
          storage: localStorage, // localStorage, sessionStorage storage 선택 default sessionStorage
        },
      ],
    },
  }
)

 

state 따로 저장 예제

export const useUserStore = defineStore('storeUser', {
  state : ()=>({
      firstName: 'S',
      lastName: 'L',
      accessToken: 'xxxxxxxxxxxxx',
  }),
  persist: {
    enabled: true,
    strategies: [
      { storage: sessionStorage, paths: ['firstName', 'lastName'] },
      { storage: localStorage, paths: ['accessToken'] },
    ],
  },
})

 

vue3에서 설정한 store 사용법

<template>
    <main>
        카운트 : {{ count.count }} //state 호출
        더블 : {{ count.doubleCount }} // getter 호출
        더블2 : {{ doubleValue }}	//
        <button @click="count.count++">플러스</button>
        <button @click="count.increment()">플러스2</button> //action 함수 호출
    </main>
</template>

<script setup>
import { useCounterStore } from '../stores/counter'; //생성한 store 추가
import { computed } from 'vue';

const count = useCounterStore();// 변수에 액세스
const doubleValue = computed(() => count.doubleCount);
</script>

 

반응형