【问题标题】:How to return promise result from Vuex action instead of the promise itself?如何从 Vuex 操作返回 Promise 结果而不是 Promise 本身?
【发布时间】:2021-05-03 13:11:50
【问题描述】:

我在我的 vuex 商店中有一个动作:

export const actions = {
  myaction() {
    return 'foo'
  }
}

我可以在mounted() 生命周期钩子中得到承诺结果(这里是foo)并在控制台中显示它吗?如果是,如何?

我试过了:

mounted() {
  console.log(
    this.$store
      .dispatch('myaction')
      .then(res => res)
  )
}

但它返回的是承诺而不是我期望的承诺结果。

【问题讨论】:

  • 我可能误解了您要查找的内容,但 .then(res => console.log(res)) 不会解决问题吗?
  • @nikoshr 我什至可以通过this.$store.dispatch('myaction').then(console.log) 在控制台中获取foo,但实际上,我需要在控制台或let myvar = this.$store.dispatch('myaction') 之类的变量中返回foo ,但是当我想要myvar中的结果时,这会返回承诺@
  • 可以,但不应该这样做,因为它违反了单向数据流范式。您的目标应该是执行一个操作、设置一些数据并使用 getter 来检索它。

标签: vue.js vuex


【解决方案1】:

这些都应该工作:

    mounted() {
      this.$store
        .dispatch('myaction')
        .then(res => console.log(res))
    }

或者如果你使用 webpack(通常使用 Babel 设置),那么你可以使用 async/await:

    async mounted() {
       const res = await this.$store.dispatch('myaction');
       console.log(res)
    }

编辑: 正如@Dan 下面提到的,虽然这会返回你的承诺值,但这不是 vuex 的预期用途。因此,返回的承诺值不一定是您在操作中定义的值。

最好在您的操作中改变存储并使用计算属性,该属性使用 getter 来检索您打算从您的操作中检索的值。这可以使用 vuex 的 mapGetters 功能非常干净地完成:link

【讨论】:

  • 这是一个反模式,你不应该关心动作的返回值。改用 state/getter。
  • 同意,我误解了 OP 的要求,我认为这是对承诺完成的确认,而不是返回要在组件中使用的值。即使那样,正如您所说,应该使用吸气剂。
猜你喜欢
  • 2018-11-26
  • 2017-06-02
  • 1970-01-01
  • 2018-12-14
  • 2017-10-31
  • 1970-01-01
  • 2021-03-17
  • 2021-02-06
相关资源
最近更新 更多