LoginSignup
0
0

More than 1 year has passed since last update.

【Vuex】ミューテーションの利用

Posted at

はじめに

こんにちは!
今回は【Vuex】ミューテーションの利用についてアウトプットしていきます!

mutationsとは

ミューテーション(mutations)とはVuexのストアの状態を変更したいときに使うものです。分かりやすくいうとハンドラに近いものです。

記述法

前記事の続きの内容でアウトプットしていきます。

store/index.js
const createStore = () => {
    return new Vuex.Store({
        //⏬stateに値を保管する処理 
        state: function() {
            return {
                message: 'Hello Vuex!'
            }
        },
        mutations:{
            updateMessage: function(state){
                // ⏬state.messageを書き換える処理
                state.message = 'Updated!'
            }
        }
    })
}
pages/index.vue
<template>
  <section class="container">
    <div>
          <!--⏬storeフォルダのstateの値messageを利用することができる-->
        <p>{{ $store.state.message }}</p>
        <!--buttonをクリックすると指定したmutationsがstore側に送られ記述した処理が行われる-->
        <button v-on:click="$store.commit('updateMessage')">Update</button>
    </div>
  </section>
</template>

index.jsにstateに続きmutationsを作り、state.messageを書き換える処理を記述します。
index.vue(テンプレート側)ではbuttonをクリックすると指定したmutationsがstore側に送られ記述した処理が行われるといったように記述します。

スクリーンショット 2021-11-09 6.17.04.png

stateで記述し<p>{{ $store.state.message }}</p>で表示させていた部分が、

スクリーンショット 2021-11-09 6.17.29.png

このようにmutationsの処理内容に書き換えられています。

値渡し

ミューテーションで値渡しする方法を記述します。

store/index.js
mutations:{
   updateMessage: function(state,payload){
      state.message = payload
   }
}
pages/index.vue
<!--⏬mutationsに値を渡すにはcommitメソッドに追加の引数を渡す。追加の引数は特定のmutationsに対する(paylod)と呼ぶ-->
<button v-on:click="$store.commit('updateMessage','Commit with payload')">Update</button>

ミューテーションで値を渡したいときは、commitメソッドの第2引数に渡したい値を入れ、mutations側の第2引数で値を受け取り、利用する記述を書くことで値を渡すことができます。

スクリーンショット 2021-11-09 6.34.58.png

このように書きかわります。

最後に

今回はミューテーションの利用についてアウトプットしました。
今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。

今後ともQiitaにてアウトプットしていきます!

最後までご愛読ありがとうございました!

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