Vue从诺言中退回

时间:2018-12-10 10:11:16

标签: vue.js promise vuejs2 vuex

我正在尝试从此调度返回一些值

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

在我的vuex动作中

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

如何将错误传回进行vuex分发的.vue文件?

3 个答案:

答案 0 :(得分:1)

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

您的状态对象将由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>

我可能是错的,但以我个人的观点,我认为使用动作来返回东西是错误的。您在使用商店时最好也可以利用它。

其他额外的好处是,您可以在.vue文件中指出api是否正在加载或成功完成。

答案 1 :(得分:1)

我最终要做的事情很简单。我把渔获物拴在了我的发件人身上:

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,
})

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

答案 2 :(得分:0)

商店:

.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)
});