
name: 'kim'이라는 state 데이터가 있고 100개의 컴포넌트에서 이를 직접 수정하게 되면, 어딘가에서 갑자기 'kim' 대신 123이라는 숫자로 바뀌는 버그가 발생할 수 있습니다.[참고: Vuex에서는 mutations를 통해 state를 변경하도록 강제함]
// Vuex (Vue2) 예시
const store = createStore({
state () {
return {
name: 'kim',
age: 20,
}
},
mutations: {
한살더하기(state) {
state.age++
}
},
})
<!-- App.vue (Vue2) -->
<button @click="$store.commit('한살더하기')">버튼</button>
Pinia에서는 mutations 대신 actions를 사용합니다. 또한 <script setup> 구문을 활용하여 간결하게 작성할 수 있습니다.
// store/user.js
import { defineStore } from 'pinia'
// `defineStore()`의 반환값에 원하는 대로 이름을 지을 수 있지만,
// `use`로 시작해 `Store`로 끝나는 Store의 이름을 사용하는 것이 좋습니다.
// (예: `useUserStore`, `useCartStore`, `useProductStore`)
// 첫 번째 인수는 애플리케이션 내 Store의 고유 ID입니다.
export const useUserStore = defineStore('user', {
state: () => ({
name: 'kim',
age: 20,
}),
actions: {
한살더하기() {
this.age++
}
}
})
아래처럼 <script setup>을 사용하여 스토어를 불러오고, 버튼 클릭 시 state를 변경하도록 구현합니다.
<!-- App.vue (Vue3 + Pinia) -->
<template>
<button @click="userStore.한살더하기()">버튼</button>
</template>
<script setup>
import { useUserStore } from './store/user'
const userStore = useUserStore()
</script>