【问题标题】:Vue returning from a promiseVue 从承诺中返回
【发布时间】:2019-05-11 05:19:53
【问题描述】:

我正在尝试从这个调度中返回一些值

 this.$store.dispatch('setValue', this.Value)
      .then(response => {
        console.log(response)
});

在我的 vuex 操作中,我有

.catch(error => {
              if (error.response.status === 412) {
                return "some message"
     }
});

如何将错误传递回进行 vuex 调度的 .vue 文件?

【问题讨论】:

  • 在 vuex 动作中使用 throw 错误。 }).catch((error) => { throw error})

标签: vue.js promise vuejs2 vuex


【解决方案1】:

我认为正确的做法是在您的store 中有一个status 属性。

您的状态对象将由error, success, loading 组成。

所以如果你的动作抛出异常,你可以这样处理:

catch (error) {
    commit("error", `Some Message`);
}

您的错误突变如下所示:

error(state, payload) {
    state.status.success = false;
    state.status.loading = false;
    state.status.error = payload || false;
}

您的模板只会在 store.state.status 上收听

<div v-if="store.state.status.error">{{store.state.status.error}}</div>

我可能是错的,但在我个人看来,我认为使用操作来返回东西是错误的。您使用商店,所以不妨尽可能地利用它。

其他额外的好处是,如果 api 正在加载或某些事情成功,您可以向 .vue 文件指示。

【讨论】:

  • 感谢 Jeremy 一个非常好的解决方案,我选择了其他看起来更容易的方法。
  • 好的,太棒了,我在我的所有项目中都使用了这种模式,到目前为止效果很好。
【解决方案2】:

我最终做的很简单。我将捕获物与我的调度联系起来:

this.$store.dispatch('setValue', this.Value)
      .then(response => {
        console.log(response)
})
.catch(error => {
              if (error.response.status === 412) {
                return "some message"
     }
});

然后我从操作中返回了 Axios 调用:

return axios({
   method: 'post',
    url: `/mypath,
    data: mydata,
    json: true,
})

这意味着我可以在我想触发操作的地方处理返回的数据/错误。

【讨论】:

    【解决方案3】:

    商店:

    .catch(error => {
      if (error.response.status === 412) {
          throw error
      }
    });
    

    带有异步方法的Vue元素:

    try{
        let response = await this.$store.dispatch('setValue', this.Value)
    } catch(error) {
        console.log(error)
    });
    

    【讨论】:

    • 不错的解决方案,我可以看到这种情况会派上用场。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2019-08-14
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多