반응형
이번 포스팅에서는 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>
반응형
'개발 > VUE' 카테고리의 다른 글
Vue - WebSocket connection failed(webpack) 해결방법 (1) | 2023.12.20 |
---|---|
Vue - v-html 사용 시 발생하는 주석 관련 에러 해결 방법 (0) | 2023.12.01 |
Vue - watch를 이용한 입력 값 제한 (0) | 2020.07.27 |
Vue - router params 새로고침 후 값이 없어질때 (0) | 2020.07.27 |
Vue - DOM 업데이트 후 작업하는 함수 $nextTick() (0) | 2020.07.01 |