JSFiddle - React, Tailwind, and code Playground
by ktsn
HTML
<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>
JavaScript
const store = new Vuex.Store({
// グローバルな名前空間にステート、ゲッター、ミューテーションを定義
state: {
count: 1
},
getters: {
double: state => state.count + state.count
},
mutations: {
update (state, payload) {
state.count = payload
}
},
modules: {
// 名前空間が区切られたexampleモジュールを定義
example: {
namespaced: true,
getters: {
// 第3引数、第4引数にグローバルな名前空間にアクセスするための
// rootState、rootGettersが渡される
triple: (state, getters, rootState, rootGetters) => {
return rootState.count + rootGetters.double
}
},
actions: {
multiplyByFive (ctx) {
// グローバルなdoubleゲッターとexampleモジュールのtripleゲッターを利用する
const five = ctx.rootGetters.double + ctx.getters.triple
// グローバルな名前空間のupdateを呼び出したいので、
// root: true オプションを付与する
ctx.commit('update', five, { root: true })
}
}
}
}
})
console.log(store.state.count) // -> 1
// exampleモジュールのmultiplyByFiveアクションを呼び出す
store.dispatch('example/multiplyByFive')
console.log(store.state.count) // -> 5