参考コード

  • store を module に分割することで、より見通しが立つ
  • modules として分割した store を登録する
/store/index.js
import Vue from "vue";
import Vuex from "vuex";

import superFunction from "./superFunction";
import header from "./header";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    superFunction,
    header
  }
});

export default store;
  • 分割された store の設定で namespaced: true とすることを忘れずに
/store/superFunction/index.js
const state = {
  appNumber: 0
};

const getters = {
  appNumber(state) {
    return state.appNumber;
  }
};

const actions = {
  changeNumber({ commit }, val) {
    commit("changeNumber", val);
  }
};

const mutations = {
  changeNumber(state, value) {
    state.appNumber = state.appNumber + value;
  }
};

const superFunction = {
  namespaced: true, // 忘れずに
  state,
  getters,
  actions,
  mutations
};

export default superFunction;
  • getter と action の参照の仕方が変わる
  • this.$store.getters["moduleName/getterName"]
  • this.$store.dispatch("moduleName/actionName")
/components/AppMain.vue
<template>
  <main>
    {{appNumber}}
    <Controller :changeNumber="changeNumber"/>
  </main>
</template>

<script>
import Controller from "./Controller";
export default {
  components: {
    Controller
  },
  computed: {
    appNumber() {
      return this.$store.getters["superFunction/appNumber"];
    }
  },
  methods: {
    changeNumber(val) {
      this.$store.dispatch("superFunction/changeNumber", val);
    }
  }
};
</script>