Mutations 란
: Vuex의 데이터 state의 값을 변경하는 로직들을 의미
* Getters와 차이점은
1. 인자를 받아 Vuex에 넘겨줄 수 있다.
2. computed가 아닌 methods에 등록
* Actions와 차이점
1. Mutations는 동기적 로직
2. Actions는 비동기적 로직
예)
return this.$store.state.counter++;
위 내용처럼 동시에 여러사람이 카운터값을 변경했을때 어느 컴포넌트에서 변경했는지 추적하기 어렵기때문에
안티패턴이 된다.
- Mutations 등록
// src/store/store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)
export const store = new Vuex.Store({
mutations: {
addCounter: function(state, payload){
return state.counter++;
}
}
})
- Mutations 사용
// App.vue
<template>
<div id="app">
<button @click="addCounter">+</button>
</div>
</template>
<script>
export default{
methods: {
addCounter() {
this.$store.commit('addCounter');
}
}
}
</script>
getters 처럼 "this.$store.mutations.addCounter" 이렇게 접근은 불가능하며
"commit" 을 사용하여 mutations를 호출한다.
- Mutations에 인자 값 넘기기
this.$store.commit('addCounter', 10);
this.$store.commit('addCounter', {
value: 10,
arr: ["a", "b", "c"]
});
mutations: {
addCounter: function(state, payload){
state.counter = payload.value;
}
}
* payload는 딱히 정해진건 아니고 변수명이다.
- mapMutations
: mapGetters 와 마찬가지로 mutations도 Vuex에 내장된 helper 함수가 존재
import { mapMutations } from 'vuex'
methods: {
// Vuex의 Mutations의 메서드 명과 해당 컴포넌트의 메서드명을 동일하게 사용하려면 [] 대괄호 사용
...mapMutations([
'addCounter'
]),
// Vuex의 Mutations의 메서드 명과 해당 컴포넌트의 메서드명을 다르게 사용하려면 {} 중괄호 사용
...mapMutations({
addCounter: 'addCounter'
})
}