mutationsについて
Vuexはグローバル変数なので、状態を変えると、stateを使っている箇所全てに影響する。
例えばこの以下の部分はデータの追跡や予測をしにくくしている
counter.js
this.$store.state.count++
これは、ぱっと見、データを変えているのか参照しているのかがわからない
mutationsを使わなくても、データを変えることはできけど
データの追跡や予測をしやすくするために、mutationsでしかstateを変えないようにした方が良いらしいです。
mutationsの書き方
counter.js
export default new Vuex.Store({
state:{
count:2
},
getters:{
doubleCount: state => state.count * 2,
tripleCount: state => state.count * 3
},
//mutationsでしかstateを変えれないようにする
mutations: {
//第一引数はstate,第二引数は適当でいいけど今回はnumber
increment(state,number){
state.count += number;
},
decrement(state,number){
state.count -= number;
}
});
double.countやtripleCountを使用している部分はどのように書くかというと
Header.vue
<template>
<div>
<button @click="increment">*2</button>
<button @click="decrement">-1</button>
</div>
</template>
<script>
export default {
methods:{
increment(){
//mutationsを用いいない書き方だと、
//this.$store.state.count++;
//引数(今回は2)もとることができる
this.$store.commit('increment',2);
},
decrement(){
this.$store.commit('decrement',2);
}
}
};
</script>
このように、stateを変える部分をこの場所一つに絞ることで、わかりやすくなります!