vue 中的多个 vuex 存储

aji*_*mar 2 vue.js vuex vuex-modules

我正在尝试在我的应用程序中实现微前端架构。我有一个公共商店,里面有所有服务中常用的所有数据。在其中一项服务中,我尝试导入公共商店并在全球范围内使用它,但我无法访问它。

例子:

在 main.js 中我正在尝试以下代码:

import Vue from "vue";
// Trying to import the common store
import commonStore from "../../common/src/store"
import router from "./router";
import store from "./store/store";

new Vue({
      router,
      store,
      commonStore
});
Run Code Online (Sandbox Code Playgroud)

在 App.vue 中,我尝试执行以下操作,但无法访问它。

mounted(){
  console.log(this.$commonStore);
}
Run Code Online (Sandbox Code Playgroud)

有什么办法,我可以在 vue.js 中使用多个商店吗?

Dan*_*iel 14

您正在寻找Modules. 在Vuex中你可以定义独立的store模块:

const commonStore = {
  state: () => ({ a: 1 }),

};

const globalStore = {
  state: () => ({ a: 2 }),
};

const store = new Vuex.Store({
  modules: {
    commonStore: commonStore,
    globalStore: globalStore
  }
})

new Vue({
  router,
  store,
});

Run Code Online (Sandbox Code Playgroud)

然后您可以通过以下方式访问模块存储:

mounted() {
  console.log(this.$store.state.commonStore.a); // => 1
  console.log(this.$store.state.globalStore.a); // => 2
}
Run Code Online (Sandbox Code Playgroud)