模块与多个 vuex 存储文件

Modules vs Multiple vuex store files

我正在使用 vue 和 vuex 开发一个项目。而且我认为大多数人都遇到了问题,一段时间后 store.js(或 index.js)变得太大了。所以我想拆分 store.js 文件。经过一些 google 我发现我可以使用模块来解决这个问题。但是我也尝试创建一个新的 vuex 实例并且它工作得很好。

Single instance with modules :
---store.js
import Vuex from "vuex";
import thisismodule1 from "./modules/module1";
import thisismodule2 from "./modules/module2";

const createStore = () => {
  return new Vuex.Store({
    modules: {
      module1: thisismodule1,
      module2: thisismodule2

    }
  });
};

export default createStore;
const store = new Vuex.Store({
module
});



Multiple files with multiple instances:
---storeCar.js
---storeHouse.js
---storeTree.js
...

所以我的问题是,这是允许的还是我必须使用单实例模块?

提前致谢!

有一个最佳实践:

  1. 创建文件。那个名字是 Shared

  1. 创建一个 Store 文件夹并在其上创建一个 modules 文件夹:

  1. 您应该在模块文件夹中添加模块并为目标定义您的商店:

例如:

import * as types from "../types";

const state = {
  currentPage: {}
};
const getters = {
  [types.avatarManagement.getters.AVATAR_MANAGEMENT_GET]: state => {
    return state.currentPage;
  }
};

const mutations = {
  [types.avatarManagement.mutations.AVATAR_MANAGEMENT_MUTATE]: (
    state,
    payload
  ) => {
    state.currentPage = payload;
  }
};

const actions = {
  [types.avatarManagement.actions.AVATAR_MANAGEMENT_ACTION]: (
    { commit },
    payload
  ) => {
    commit(types.avatarManagement.mutations.AVATAR_MANAGEMENT_MUTATE, payload);
  }
};

export default {
  state,
  getters,
  mutations,
  actions
};

  1. 创建 index.js 以定义 Vuex 并导入您的模块:

index.js 文件:

import Vue from "vue";
import Vuex from "vuex";
import avatarManagement from "./modules/avatarManagement";

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    avatarManagement
  }
});
5) also you can types of your vuex store on Type.js file:

type.js:



        export const avatarManagement = {
      getters: {
        AVATAR_MANAGEMENT_GET: "AVATAR_MANAGEMENT_GET"
      },
    
      mutations: {
        AVATAR_MANAGEMENT_MUTATE: "AVATAR_MANAGEMENT_MUTATE"
      },
    
      actions: {
        AVATAR_MANAGEMENT_ACTION: "AVATAR_MANAGEMENT_ACTION"
      }
    };



***从商店获取数据:

  computed: {

    ...mapGetters({
      registrationData:types.avatarManagement.AVATAR_MANAGEMENT_GET,

    getDataFromStore() {
      return this.registrationData;
    }
}
***for Change data to Store and mutate that:


      methods: {
        goToActivity() {
          const activity = {
            companyList: this.categories
          };
          this.$store.commit(types.avatarManagement.AVATAR_MANAGEMENT_MUTATE, {
            newData
          });
        },
    }