LoginSignup
0
0

More than 3 years have passed since last update.

mutationsについて学んだことの備忘録

Posted at

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を変える部分をこの場所一つに絞ることで、わかりやすくなります!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0