vue3를 학습하는 과정에서 pinia를 사용한 상태관리를 경험하고 기존에 사용했던 vuex와의 다른점에 대해서 비교하는 내용을 정리해보기로 했다.
//main.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
Vuex 라이브러리를 불러오고 Vue에 연결한다.
//store/index.js
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
스토어를 생성 뒤 로직을 구현한다.
mutations는 state의 값을 변경하기 위한 속성으로 actions는 commit 함수를 사용해 mutation을 호출하여 상태를 변경한다.
//App.vue
<template>
<div id="app">
<p>{{ count }}</p>
<button @click="incrementAsync">증가</button>
</div>
</template>
<script>
export default {
computed: {
count () {
return this.$store.state.count
}
},
methods: {
incrementAsync () {
this.$store.dispatch('incrementAsync')
}
}
}
</script>
이후 컴포넌트에서 store의 데이터에 접근할 시 this.$store 속성을 사용하여 접근하게 된다.
//main.js
import Vue from 'vue'
import { createPinia } from 'pinia'
Vue.use(createPinia())
Pinia 라이브러리를 불러오고 Vue에 연결한다.
//store/index.js
import { defineStore } from 'pinia'
export const useStore = defineStore({
id: 'main',
state: () => ({
count: 0
}),
getters: {
doubleCount() {
return this.count * 2
}
},
actions: {
increment() {
this.count++
}
}
})
스토어를 생성 뒤 로직을 구현한다.
pinia에서는 state의 값을 변경할 시 muations속성을 사용하지 않고 getter와 actions속성에서 값을 변경할 수가 있다.
//App.vue
<template>
<div id="app">
<p>{{ count }}</p>
<p>{{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useStore } from './store'
const store = useStore()
const count = ref(store.count)
const doubleCount = ref(store.doubleCount)
const increment = store.increment
</script>
이후 컴포넌트에서 store의 데이터에 접근할 시 해당 store를 import하여 템플릿 내에서 접근한다.
Vuex는 new Vuex.Store로 스토어를 생성하는 반면에 Pinia는 defineStore 함수를 사용해 스토어를 정의하고 필요할 때마다 해당 스토어를 사용한다.
Vuex에서는 commit 함수를 사용해 mutation을 호출하여 상태를 변경한다.
반면에 Pinia에서는 스토어의 메소드를 직접 호출하여 상태를 변경한다.
Vuex에서는 this.$store를 통해 스토어에 접근한다.
반면에 Pinia에서는 store를 import하여 스토어 인스턴스에 직접 접근한다.