【问题标题】:Multiple vuex store in vuevue中的多个vuex存储
【发布时间】:2021-08-14 13:19:18
【问题描述】:

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

示例:

在 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
});

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

mounted(){
  console.log(this.$commonStore);
}

有什么办法,我可以在vue中使用多个商店。

【问题讨论】:

  • 你读过VueX Modules吗?我认为这就是您所说的“多家商店”。为什么需要 main.js 中的 store?只在单个组件中导入 store 还不够吗?

标签: vue.js vuex vuex-modules


【解决方案1】:

您正在寻找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,
});

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

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

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 2021-07-25
    • 1970-01-01
    • 2021-09-02
    • 2020-11-17
    • 2019-09-09
    • 2018-01-12
    • 2022-01-24
    • 2020-04-28
    相关资源
    最近更新 更多