Vue.js Vue从承诺中回归
我正在尝试从这个分派返回一些值Vue.js Vue从承诺中回归,vue.js,promise,vuejs2,vuex,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"
this.$store.dispatch('setValue', this.Value)
.then(response => {
console.log(response)
});
在我的vuex动作中
.catch(error => {
if (error.response.status === 412) {
return "some message"
}
});
如何将错误传递回进行vuex分派的.vue文件?存储:
.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)
});
我认为正确的方法是在
商店中设置status
属性
您的状态对象将由错误、成功、加载
组成
因此,如果您的操作引发异常,您可以如下处理:
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>
{{store.state.status.error}
我可能错了,但在我个人看来,我觉得用行动退货是错误的。您可以使用商店,以便尽可能充分利用它
其他额外的好处是,您可以向您的.vue文件指示api是否正在加载,或者什么时候加载成功。我最后做的事情非常简单。我把捕获物拴在我的调度上:
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,
})
这意味着我可以在希望触发操作的地方本地处理返回的数据/错误。在vuex操作中使用throw error。})。catch((error)=>{throw error})谢谢Jeremy,这是一个非常好的解决方案,我选择了其他似乎更简单的方法。好吧,太棒了,我在我所有的项目中都使用了这个模式,到目前为止效果非常好。很好的解决方案,我可以看到一种情况,这将派上用场。