【问题标题】:Unable to get rootState in getter无法在 getter 中获取 rootState
【发布时间】:2017-02-11 00:50:58
【问题描述】:

为什么 Vuex 模块中的这个简单的 getter 不能按照API reference 所说的那样做?

const getters = {
  myGetRootState: (state, rootState) => {
    return rootState
  }
}

上面的 Getter 返回当前模块状态,而不是存储状态。

还有这个

const getters = {
  myGetRootState: rootState => {
    return console.log(rootState.anyModuleYouWant)
  }
}

未定义的日志。我尝试了许多上下文和返回值的排列,但无济于事。

知道为什么会这样以及如何让它达到预期的效果吗?

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    模块 getter 接受 3 个参数(本地状态、getter、根状态)。

     const getters = {
    
       myGetRootState (state, getters, rootState){
        console.log("rootState.exampleVar = "+ rootState.exampleVar)
        return rootState.exampleVar
       }
    }
    

    在 Vue 实例组件中使用:

    computed: {
       myGetRootState: function(){
                return this.$store.getters.myGetRootState
            }
    }
    

    您无需在 Vue 实例中指定模块。

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 2021-07-29
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2013-08-15
      • 1970-01-01
      相关资源
      最近更新 更多