【问题标题】:how to acces getter from module vuex如何从模块 vuex 访问 getter
【发布时间】:2021-02-13 16:01:23
【问题描述】:

我在 vuex 中创建了模块,但是如何在计算中访问 getter? 这是产品模板

<template>
    <ul>
        <li v-for="item in productAll" :key="item._id">
            <p>hello word</p>
        </li>
    </ul>
</template>

<script>
export default {
    
    computed:{
        productAll(){
            return this.$store.getters.productAll
        }
    },
}
</script>

这是我的商店

const productModule = {
  state: () => ({
    product: [

    ]
  }),
  getters:{
    productAll(context){
      return [
        "123","456"
      ]
      // return state.product.data
    }
  },
}

export const store = new Vuex.Store({
  modules: {
    productModule
  },
}

我只在“store.getters.productAll”中返回数组 123 345,如果我将数组 123 345 放入计算它正在工作,将显示 hello word 2 次,但是为什么当我放入 store 模块时它不起作用?

【问题讨论】:

  • 您的代码看起来还不错。您确定您的商店导入正确吗?

标签: vue.js vuex vuex-modules


【解决方案1】:

与动作不同,getter 不会收到 context 对象。他们收到 4 个参数:

(state, getters, rootState, rootGetters)
  • state: 当前模块状态
  • getters: 当前模块获取器
  • rootState:根模块状态(以及模块间访问)
  • rootGetters:根模块获取器(以及模块到模块的访问)

所以以这种方式创建你的吸气剂:

getters: {
  productAll(state) {
    return state.product.data
  }
}

【讨论】:

  • 谢谢,需要澄清一下.. 1. state:当前模块状态 2. getters:我们可以访问当前模块 getter。 3. rootState:我们可以访问其他模块的状态。 4. rootGetters:我们可以访问其他模块的getter。请纠正我,如果我在这里错了..
  • @HarshaVardhan 嗨,是的,你明白了。我会更新我的答案以显示更多详细信息。
  • 仍然不工作,我事件没有访问阶段,我只在 store.getter 中返回数组 [123,345] 但没有显示 hello word 2 次,这个 getter 在 productModule 下
  • 可能是因为product是一个数组而不是一个对象,所以product.data没有意义。
猜你喜欢
  • 2018-02-10
  • 2021-09-15
  • 2019-11-17
  • 2017-10-01
  • 2021-07-06
  • 2021-04-26
  • 2021-09-04
  • 2021-05-15
相关资源
最近更新 更多