はじめに
こんにちは!
今回は【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側に送られ記述した処理が行われるといったように記述します。
state
で記述し<p>{{ $store.state.message }}</p>
で表示させていた部分が、
このように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引数で値を受け取り、利用する記述を書くことで値を渡すことができます。
このように書きかわります。
最後に
今回はミューテーションの利用についてアウトプットしました。
今回の記事を読んで質問、間違い等あればコメント等頂けると幸いです。
今後ともQiitaにてアウトプットしていきます!
最後までご愛読ありがとうございました!