티스토리 뷰

Frontend/Vue.js

[Vue.js3] Pinia 란?

Mo'Greene 2023. 6. 19. 17:02

 

https://mo-greene.tistory.com/97

 

[Vue.js3] Vuex란

애플리케이션이 복잡해지고 컴포넌트 수가 많아지면, 컴포넌트 간의 데이터 전달 및 관리가 점점 더 어려워진다. 기본적으로 Vue.js2에선 자식 컴포넌트간 데이터를 전달하는 eventBus가 있었지만 V

mo-greene.tistory.com

전에 포스팅한 중앙 집중식 상태관리 저장소 Vuex

따지고 보면 Vuex의 생김새는 Vue.js3에서 강조하는 CompositionAPI가 아닌 OptionsApi의 형태를 보이고 있다.

 

https://vuex.vuejs.org/
 

What is Vuex? | Vuex

What is Vuex? Pinia is now the new default The official state management library for Vue has changed to Pinia. Pinia has almost the exact same or enhanced API as Vuex 5, described in Vuex 5 RFC. You could simply consider Pinia as Vuex 5 with a different na

vuex.vuejs.org

현재 Vuex 메인페이지에 소개되어있는 문구

Pinia is now the new default??

Vuex에서 향후 업그레이드를 지원하지 않는다고 적혀있다.

 

pinia는 composition 방식으로 상태관리 기능을 제공해주는 라이브러리 이다.

현재는 pinia가 vue 애플리케이션의 공식 상태관리 라이브러리가 되었다.

 

pinia와 vuex의 차이점을 알아보려고 한다.

 


구조

Vuex 공식사이트 아키텍처

Vuex는 스토어 내부에 state, mutations, action을 포함하면서 하나하나 dispatch()메서드를 이용해 actions와 payload를 호출해야되는 반면

 

Pinia의 경우, 스토어 내부에 actions와 state만을 정의하고 직접 액션 메서드를 호출한다.

또한 Vuex의 경우 Mutations에서 상태(state)를 관리할 수 있어 매번 코드의 양이 늘어 보기 불편하고 귀찮았다.

헌데 Pinia는 액션에서도 상태를 변경할 수 있다고 하니 충분히 구조적으로 간단하고 직관적이 되었다.

 


Store

Vuex는 단일 스토어를 사용하여 상태를 관리해야 했다.

점점 애플리케이션이 커질수록 Vuex는 보기 불편하더라도 하나의 상태관리에서 관리하거나

하위 모듈을 작성하여 분리해 관리 해야했다.

하위 모듈의 등록은 간단히 들릴지 모르나, 네임스페이스를 지정해야 하는 등 번거로움이 많다.

 

하지만 Pinia는 여러개의 스토어를 사용할 수 있다는 장점이 있다.

 


CompositionApi

Vue.js3로 버전업이 된지 몇년이 지났고 슬슬 앞서 개발된 Vue.js2에서 Vue.js3의 CompositionApi를 통한 업그레이드가 진행되고 있다.

Pinia는 스토어를 정의할 때 optionApi와 composition을 고를 수 있으므로 옵션api만을 지원하는 Vuex보다 훨씬 취향에 따라 개발할 수 있게 되었다.

 


Pinia => Options, Composition 예제

import { defineStore } from 'pinia'
import { reactive, computed } from 'vue'

//optionsApi
export const useCount1Store = defineStore('count1', {
	state : () => ({
		count : 0
	}),
	actions: {
		increment({ num }) {
		this.count += num;
		},
	}
})

//compositionApi
export const useCount2store = defineStore('count2', () => {
	const state = reactive({ count : 0 })
	const increment = ({num}) => {
		state.count += num;
	}
	const count = computed(()=>state.count);

	return {count, increment};
})

 

'Frontend > Vue.js' 카테고리의 다른 글

Vue.js3 Login + JWT 토큰  (0) 2023.07.11
[Vue.js3] Vuetify Validation : Rules  (0) 2023.07.01
[Vue.js3] <script> or <script setup>  (0) 2023.06.28
[Vue.js3] Vuex란  (0) 2023.05.19
Vue.js3 구조 이해  (0) 2023.04.21
Comments