#クラシックモード
store/index.js
import Vuex from "vuex"
const createStore = () => {
return new Vuex.Store({
state() {
return {
count: 0
};
},
getters: {
getCount: state => state.count
},
mutations: {
incrementCountMutations(state) {
state.count++;
}
},
actions: {
incrementCountActions({ commit }) {
commit("incrementCountMutations");
}
}
});
};
export default createStore
#モジュールモード
動作条件
・index.jsがstoreオブジェクトをexportしない
・store配下にindex.jsが存在しない
store配下にcounter.jsを作成
store/counter.js
export const state = () => ({
count: 0
})
export const getters = {
getCount: state => state.count
}
export const mutations = {
incrementCountMutations(state) {
state.count++;
}
}
export const actions = {
incrementCountActions({ commit }) {
commit("incrementCountMutations");
}
}
呼び出す(counter.jsの場合)
pages/index.vue
<template>
<div>
state : {{ $store.state.counter.count }}
<br>
getters : {{ $store.getters['counter/getCount'] }}
<br>
<button @click="$store.commit('counter/incrementCountMutations')">incrementCountMutations</button>
<br>
<button @click="$store.dispatch('counter/incrementCountActions')">incrementCountActions</button>
</div>
</template>
#ヘルパー関数を使用する
pages/index.vue
<template>
<div>
state : {{ count }}
<br>
getters : {{ getCount }}
<br>
<button @click="incrementCountMutations">incrementCountMutations</button>
<br>
<button @click="incrementCountActions">incrementCountActions</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
computed: {
...mapState('counter', [
'count'
]),
...mapGetters('counter', [
'getCount'
])
},
methods: {
...mapMutations('counter', [
'incrementCountMutations'
]),
...mapActions('counter', [
'incrementCountActions'
])
}
}
</script>