Vue에서 Pinia Store를 사용해보자.

2024. 1. 5. 15:01뷰(Vue)

반응형

 

 

상태관리 라이브러리의 경우

Vuex와 Pinia가 있다. 2개를 비교하는 글의 경우 인터넷에 많이 있기 때문에 검색을 추천한다.

간단한 설명으로는 pinia가 이후에 나온 것이므로 조금 더 직관적이고 Vue3에서 주로 사용하는 Composition API를 기준으로 동작한다는 것이다.

그리고 다중 store를 지원한다.

Vuex ↔ Pinia 구조 차이(다중store 지원).

타입스크립트 지원.

Composition API 지원. (Vue3 기준 common)

등이 있다.

 

설치

npm install pinia

현재프로젝트기준 "pinia": "^2.1.7", 이 설치됨

main.js 에 추가 적용

import { createPinia } from 'pinia';
const pinia = createPinia();

createApp(App).use(pinia).mount('#app')

기본적인 틀은 아래와 같음. 예시코드 counter로 명명된 곳에 스토어별 고유한 이름이 필요하다.

import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
  state: () => ({ 
		name: '',
		count: 0, 
	}),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

위 방식은 기본적으로 제공하는 option방식이라고 한다.

내가 중심으로 짜려고 하는 setup 방식은 다음과 같이 변경됨

  • ref() - Option의 state 속성
  • computed() - Option의 getters
  • function() - Option의 actions

sidebar를 컨트롤 하는 형태로 state를 선언하여 사용하고 싶었다.

다음과 같이 store를 정의했다.

import {defineStore} from "pinia";
import {ref, computed } from "vue";

export const commonStore = defineStore('commonStore', () => {
    //state
    let sideBarVisible = ref(true);
    //getter
    const getSideBarIsVisible = computed(() => sideBarVisible);

    //actions
    function toggleVisibility() {
        const contentContainer = document.querySelector('#content-concon');
        //보일때
        if (sideBarVisible) {
            contentContainer.style.marginLeft = '0px';
        //안보일때
        } else {
            contentContainer.style.marginLeft = '225px';
        }
        document.body.classList.toggle('sidenav-toggled');
        sideBarVisible.value = !sideBarVisible.value;
    }
    //return
    return { sideBarVisible, getSideBarIsVisible, toggleVisibility };
});

사용하는 측에서는 스토어를 불러와서 담아서 쓸 수 있었다.

import { commonStore } from '@/store/index.js';
import {storeToRefs} from "pinia";
const store = commonStore();
const {toggleVisibility} = store;
const {getSideBarIsVisible} = storeToRefs(store);
let check = getSideBarIsVisible;

반응형을 유지하기 위해서는 storeToRefs를 사용해서 감싸줘야한다.

action의 경우에는 그냥 호출해야지 문제없이 동작하지만.

기본적으로 state로 명시되어있는 값을 사용하는 getter나 state(ref, reactive)영역의 경우 storeToRefs로 감싸서 호출해야지만 정상적으로 동작하는 걸 보장한다. (pinia 기본 권장사항.)

해당부분에 대한 설명은 pinia 공식 홈페이지에 자세히 설명되어 있다.

(defining a store 파트)

Pinia 🍍

 

Pinia | The intuitive store for Vue.js

Intuitive, type safe, light and flexible Store for Vue

pinia.vuejs.org

2개의 선언방식의 차이

참고주소

Choosing Between Two Store Syntaxes in Pinia

 

Choosing Between Two Store Syntaxes in Pinia

The Problem The Pinia docs offer two distinct syntax for writing Pinia stores.  Option Store  Setup Store However when asked, “Which syntax should I pick”, the docs simply say to “pick the one that you feel the most comfortable with”.   “You d

www.simplethread.com

그리고 참고로 state에 선언되는 ref, reactive의 차이점

ref 에서는 String , Number , Object 등 어떠한 타입에서도 사용할 수 있습니다. 반면 reactive 에서는 Object , array , Map , Set 과 같은 타입에서만 사용할 수 있습니다.

참고주소

[Vue.js] Vue3에서 ref와 reactive 사용법과 차이점

 

[Vue.js] Vue3에서 ref와 reactive 사용법과 차이점

ref와 reactive, 뭐가 다른 건데? 어떤 것을 사용해야 하는 건데?

velog.io

 

반응형