Vuex 와 같은 상태 관리 라이브러리 이며 Vue 2 와 Vue 3 모두에서 작동한다.
본 글에서는 Vue 3 에 대해서만 다룬다.
터미널에 다음과 같은 명령어로 설치한다.
yarn add pinia
# or with npm
npm install pinia
main.js 에 다음 코드를 작성하여 Pinia 를 사용하도록 한다.
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
import { defineStore } from 'pinia'
export const useStore = defineStore('main', {
})
'defineStore()' 의 리턴 값은 'use'와 'Store'로 이루어진 이름이 좋다.
('useUserStore', 'useCartStore', 'useProductStore', ...)
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
defineStore() 의 두번째 인자에 Options Object 를 전달하는 방법이다.
Vue 의 Options Api 와 유사하다.
state 는 Data, getters 는 computed, actions 는 methods 라고 생각할 수 있다.
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
defineStore() 의 두번째 인자에 Setup function 전달하는 방법이다.
Composition Api 의 Setup 함수와 유사하다.
Setup Stores 에서는 ref() 가 state, computed() 가 getters, function() 이 actions 라고 보면 된다.
import { storeToRefs } from 'pinia'
export default defineComponent({
setup() {
const store = useStore()
// `name` and `doubleCount` are reactive refs
// This will also create refs for properties added by plugins
// but skip any action or non reactive (non ref/reactive) property
const { name, doubleCount } = storeToRefs(store)
// the increment action can be just extracted
const { increment } = store
return {
name,
doubleCount,
increment,
}
},
})