【问题标题】:How to Vuex state with a getter within a module from another module如何使用来自另一个模块的模块内的 getter 进行 Vuex 状态
【发布时间】:2019-09-04 14:18:49
【问题描述】:

我正在用 VueJS 构建一个应用程序,但是 Vuex 模块给我带来了一些问题。

当我从另一个模块调用它时,我无法检索模块中的状态。

在我的 Vue Devtools Vuex getter 中: modA/mycustomer: 未定义

我已经阅读了 Vuex 网站上的所有文档,并尝试了一些在 stackoverflow 中已经给出的解决方案,但我迷路了。可能忽略了一些东西

我的商店.js

  export default new Vuex.Store({
    modules: {
      modA: moduleA,
      modB: moduleB
    }
  })

模块A JS

  export default {
    namespaced: true,
    state:{
       customerId:0
    },
    getters: {
       customerId: state => {
          return state.customerId
       }      
    }
  }

moduleB.js

   export default {
     namespaced: true,
     state:{
       orderId:0
    },
     getters: {
       orderId: state => {
          return state.orderId
       },
       mycustomer: rootGetters => {
          return rootGetters['modA/customerId']
       }
     }
  }

我通常希望通过此请求获得 customerId。但只有未定义 跨模块需要一些状态。

【问题讨论】:

    标签: vue.js module vuex getter


    【解决方案1】:

    相关文档是Accessing Global Assets in Namespaced Modules,上面写着:

    如果您想使用全局状态和 getter,rootStaterootGetters 作为 第三和第四个参数传递给 getter 函数,并且还作为传递给的上下文对象的属性公开动作函数。

    所以如果你想在modB模块中的mycustomergetter中访问modA模块的customerIdgetter,应该是:

    mycustomer(state, getters, rootState, rootGetters) {
      return rootGetters['modA/customerId']
    }
    

    【讨论】:

    • 谢谢,现在我知道我错过了什么。我的错误是只接受一个论点。它解决了这个问题。干得好!
    • 这个函数不需要调用吗?否则你只是返回 getter 函数
    • @Emobe 不,您不调用 getter,它们是使用 Object.defineProperty 重新注册的,因此它们只是属性。
    猜你喜欢
    • 2017-07-25
    • 2017-12-08
    • 2018-02-10
    • 2017-05-12
    • 2018-05-02
    • 2021-08-27
    • 2019-11-17
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多