🦓 [WIP]Vuexの仕組みとコードの書き方について
作成日: 2022/01/18
1

Vuexをインストール

Vuexを設定する.jsファイル

src/main.js (エントリーポイント)

※Vuex読み込み記述を書く

import store from './store'
new Vue({
  store
})

src/store/index.js

※処理する記述を書く

役割 備考
state 初期値を設定する
(dataみたいなもの)
mutations stateの値を変更する 引数は(state[, payload])
actions mutationsを呼び出す 引数は(context[, payload])
getters 引数は(state)
  • 「mutationsを呼び出す」とは・・・。.vueファイルで呼び出しているのではないのか?
const store = new Vuex.store({
	state: {
		XXXX
	},
	mutations: {
		XXXX
		//書き方例
	    increment(state) {
	      state.count++
	    }

	    //第二引数がある場合
	    addCount(state, payload) {
	      state.count += payload.value
	    }
	},
	actions: {
		XXXX
		//書き方例
	    incrementAction(context) {
	      context.commit('increment')
	    }
	    //または(どちらでもOK・こっちの方が楽)
	    incrementAction({commit}) {
	      commit('increment')
	    }

	    //第二引数がある場合
	    addCountAction({commit}, payload) {
	      commit('addCount', payload)
	    }
	},
	getters: {
		XXXX
	},

})

.vueファイルで設定済Vuexを使用する

テンプレート側(templateタグ内で使用)

//state
$store.state.XXXX

//getters
$store.getters.XXXX
//または
$Store.getters('XXXX')


//mutations (※commitになるので注意)
$store.commit('XXXX')

//actions (※dispatchになる)
$store.dispatch('XXXX')

スクリプト側(scriptタグ内で使用)

書き方 引数
state this.$store.state
getters this.$store.getters
mutations this.$store.commit 【第一引数】
src/store/index.jsの
mutationsで設定した関数名

【第二引数】
第二引数がある場合もある
actions this.$store.dispatch
methods: {
    this.$store.state.XXXX
    //または
    this.$store.commit('')

    //書き方例
	increment() {
	    this.$store.dispatch('incrementAction')
    }
    addCount() {
        this.$store.dispatch('addCountAction', {
			value: 10
		})
    }
}
  • mutationsconsoleのvue(Switch to vue)で履歴を辿ることが可能。

mapヘルパーを使う


事業会社にてコーダーをしています。制作は6年目。 インプットしたことをアウトプットしています。