如何订阅商店模块

时间:2017-10-20 19:13:12

标签: vue.js vuex

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

在我的应用程序中,我有一个包含许多模块的商店,并希望subscribe仅限于特定模块,而不必具有此类逻辑if (mutation.type != thisModule.type) return;

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

3 个答案:

答案 0 :(得分:2)

您可以尝试:

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

答案 1 :(得分:1)

根据此链接,我遇到了同样的问题,并遇到了这个问题: 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()方法进行检查,因为我的模块均未以相同的方式开始,但是您可以对自己的项目使用更准确的检查

答案 2 :(得分:-3)

看起来你已经过度复杂了。 访问模块的最佳方法是将其包含在商店实例的const moduleA = { state: { ... }, mutations: { ... }, actions: { ... }, getters: { ... } } const moduleB = { state: { ... }, mutations: { ... }, actions: { ... } } const store = new Vuex.Store({ modules: { a: moduleA b: moduleB } }) 属性中。

{ path: '', redirectTo: 'pages/users', pathMatch: 'full' }
相关问题