【问题标题】:Vuex: referencing the modules variable inside actionVuex:在动作中引用模块变量
【发布时间】:2020-03-04 11:30:52
【问题描述】:

我的 Vue 应用程序中有以下全局存储:

// N.B. These Stores Are Modularised, please reference: [https://vuex.vuejs.org/guide/modules.html] for details.
const store = new Vuex.Store({
  modules: {
    surfers: surfers,
    surfSites: surfSites,
    surfTickets: surfTickets
  },
  actions: {
    resetAllState: ({ dispatch, modules }) => {
      console.log(modules); // Undefined
      console.log(store.modules); // Undefined
      console.log(this.modules); // Error in v-on handler: "TypeError: _this is undefined"
      for (const currentModule in modules) {
        console.log(`Resetting Module State: ${module}`);
        if (modules[currentModule].state.hasOwnProperty("initialState")) {
          dispatch("resetModuleState", currentModule);
        }
      }
    },
    resetModuleState: (currentModule) => {
      console.log(`Resetting Module State: ${currentModule}`);
    }
  }
});

我的目标是动作将循环通过模块,并发送一个重置状态动作,当我注销当前用户时调用它。

但是,modules 未定义,store.modulesthis.modules 都未定义或通过未定义相关错误...

那么,如果可能的话,我该如何以这种方式动态访问模块?

【问题讨论】:

  • 模块不应该被直接访问。可能应该通过迭代根状态键来完成。
  • @Wind Up Lord Vexxos 让我知道以下答案是否解决了您的问题
  • @chans 欣赏答案,但不幸的是,不是。我得到了同样的Error in v-on handler: "TypeError: _this is undefined"
  • @WindUpLordVexxos,感谢您的回复,我们可以解决您的问题,让我们知道您现在遇到了什么错误
  • @chans 谢谢。请参阅下面的回复:)

标签: javascript vue.js vuex


【解决方案1】:

上面的代码有问题,动作只能访问

{ commit, dispatch, getters } as params

但您尝试在参数中传递模块,但您仍然可以通过以下方法访问模块

在“resetAllState”操作中使用此代码

resetAllState: function ({ dispatch }) {
  for (const currentModule in modules) {
    this._modules.root.forEachChild((childModule) => {
      console.log(childModule);
    });
    //if (modules[currentModule].state.hasOwnProperty("initialState")) {
    //  dispatch("resetModuleState", currentModule);
    //}
  }
},

【讨论】:

  • 不幸的是,我仍然收到Error in v-on handler: "TypeError: _this is undefined",删除您的代码会删除控制台中的错误...
  • 放入console.log(this)并检查该对象内的值,您将可以访问当前存储,这样您就可以访问模块
  • console.log(this) is undefined`.
  • 检查答案中的更新代码并尝试,现在查看控制台日志消息
  • 用普通的javascript函数替换箭头函数
猜你喜欢
  • 2019-04-15
  • 2017-10-13
  • 2021-09-30
  • 2015-12-30
  • 2019-06-20
  • 2019-12-25
  • 2018-12-21
  • 2022-01-05
  • 2017-11-20
相关资源
最近更新 更多