【问题标题】:How to subscribe to a store module如何订阅商店模块
【发布时间】:2018-04-02 00:34:39
【问题描述】:

我知道在 Vuex 中我们可以执行 store.subscribe 并且我们会传递一个回调,该回调会在商店的每次更改时调用。

在我的应用程序中,我有一个包含许多模块的商店,并且只想 subscribe 到一个特定的模块,而不必有这种逻辑 if (mutation.type != thisModule.type) return;。

是否可以只订阅某些模块? Could not find it in the docs.

【问题讨论】:

  • 您应该可以通过this.$store.moduleName访问每个模块。试试是否有 subscribe 方法 - 它应该可以工作。我无法测试它,但我记得以前有类似的东西..
  • @AndreyPopov 这种方法行不通。

标签: vue.js vuex


【解决方案1】:

你可以试试:

store.subscribe((mutation, state) => {
  const pieces = mutation.type.split('/')
  if (pieces.length > 1) {
    const module = pieces[0]
  }
})

【讨论】:

  • 这可行,但最好简化更多代码。
【解决方案2】:

根据此链接,我遇到了同样的问题并遇到了这个问题: https://forum.vuejs.org/t/vuex-subscribe-and-modules/36049 订阅始终是全球性的。

我的解决方法是检查每个订阅中的突变:

假设你有一个订阅模块'yourmodule',你可以这样做:

store.subscribe((mutation, state) => {
  if (mutation.type.startsWith("yourmodule")){
    //do your stuff here
  }
})

mutation.type 会给出实际的突变名称,例如'yourmodule/yourcommit',我使用startswith() 方法来检查,因为我的模块都没有相同的开头,但是你可以对你自己的项目使用更准确的检查.

【讨论】:

    【解决方案3】:

    好像你把它复杂化了。 访问模块的最佳方法是将其包含在 store 实例的 modules 属性中。

    const moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    
    const store = new Vuex.Store({
      modules: {
        a: moduleA
        b: moduleB
      }
    })
    

    【讨论】:

    • 我就是这么做的。我的问题是:例如,我如何仅订阅 modules.a 中的突变?
    • 不清楚你在 vuex 上下文中所说的“事件”是什么意思。
    • 我没有在任何地方使用过events这个词。你认为我的问题值得-1吗?
    猜你喜欢
    • 2019-07-29
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多