首页 文章

Vue从承诺中回来

提问于
浏览
1

我试图从这个调度中返回一些值

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

    商店:

    .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)
    });
    
  • 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文件指明 .

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

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

相关问题