如何访问 Vuex 模块的 getters 和 mutations?

How to access Vuex module getters and mutations?

我正在尝试切换到使用 Vuex 而不是我自己开发的商店对象,我必须说我没有找到像 Vue.js 世界其他地方一样清晰的文档。假设我有一个名为 'products' 的 Vuex 模块,它有自己的状态、突变、getter 等。我如何在那个名为 'clearWorking Data' 的模块中引用一个动作?文档给出了访问模块状态的示例:

store.state.a // -> moduleA's state

但是关于吸气剂、突变、动作等,我什么都看不到

在您的示例中,它将是 store.dispatch('products/clearWorkingData') 您可以将 actions/mutations 视为某种文件系统。模块嵌套越深,它们在树中的位置就越深。

所以如果你有一棵三层深的树,你可以去 store.commit('first/second/third/method')

除了已接受的答案之外,我还想为您提供答案中缺少的 getter 的解决方法。

调试商店
在任何情况下,您都可以调用 console.log(this.$store) 来调试商店。
如果这样做,您会看到 getter 的名称中带有命名空间前缀。

访问命名空间 getter

this.$store.getters['yourModuleName/someGetterMethod']

调度命名空间

this.$store.dispatch('yourModuleName/doSomething')

使用参数命名空间的调度

this.$store.getters['yourModuleName/someGetterMethod'](myParam)

结论
关键是像 Justin 解释的那样像文件系统一样处理命名空间。

编辑:找到了一个很好的库来处理 vuex 存储
除了基本知识之外,我还想添加这个 vuex 库作为一个很好的补充,以便有效和快速地使用 vuex 商店。 https://github.com/davestewart/vuex-pathify.
它看起来很有趣,并且关心你的大部分配置,还允许你直接使用 vuex 处理 2waybinding。

** 编辑:感谢其他答案。为完整性添加了带参数的调度方法。

作为已接受答案的另一个补充,如果您需要将参数传递给 getter(例如从商店集合中获取特定项目),则需要按如下方式传递:

this.$store.getters['yourModuleName/someGetterMethod'](myParam)

我不认为我很喜欢这种表示法,但它确实如此 - 至少目前如此。

使用 Vuex mapGetters 和 mapActions,你现在可以很容易地做到这一点。但我同意,它在文档中仍然不是很明显。

假设您的商店模块 'products' 有一个名为 'mostPopular' 的 getter 和一个名为 'clearWorkingData' 的操作:

<template>
 <div>
  <p>{{mostPopularProduct}}<p>
  <p><button @click="clearProductData">Clear data</button></p>
 </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";

export default {
 computed: mapGetters({
  mostPopularProduct: "products/mostPopular"
 }),
 methods: mapActions({
  clearProductData: "products/clearWorkingData"
 })
}
</script>

mapGetters 助手简单地将存储 getter 映射到本地计算属性:

    import { mapGetters } from 'vuex'

    export default {
  // ...
  computed: {
    // mix the getters into computed with object spread operator
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}
If you want to map a getter to a different name, use an object:

    ...mapGetters({
  // map `this.doneCount` to `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

试试这个方法!

getCounter(){
  return this.$store.getters['auth/getToken'];     
}

auth 是我的模块名称,getToken 是我的 getter.

配置特定商店对象时,您必须注意使用 namespaced: true