如何订阅商店模块

How to subscribe to a store module

我知道在 Vuex 中我们可以做 store.subscribe 并且我们传递一个回调,在商店中的每个变化时调用。

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

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

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

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA
    b: moduleB
  }
})

我遇到了同样的问题并遇到了这个问题,根据这个link: 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会给出实际的mutation名称,比如'yourmodule/yourcommit',我用startswith()方法检查,因为我的none模块都是一样的,但是你可以对自己的项目使用更准确的检查。

你可以试试:

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