【发布时间】:2019-10-22 10:34:54
【问题描述】:
一般来说,我喜欢将 vuex 操作背后的大部分逻辑保留在我的模块中,这样我就可以保持组件干净,并且大部分逻辑都收集在模块中(这对我来说似乎是最佳选择),问题是有时我需要在动作完成后(通常涉及 axios 承诺)完成后在组件数据中执行一些动作(例如,在成功的 ajax 调用后清除表单),我想我通过在我的 vuex 动作调用中添加一个 then 闭包并返回 axios 来解决这个问题promise 在我的模块中,但我注意到 then 闭包将始终立即解决,而不是仅在一切正常时才解决,200 OK。
这是我的组件:
stripeSourceHandler: function(sourceId)
{
if(this.customerSources.length == 0)
{
console.log('createSourceAndCustomer');
this.createSourceAndCustomer({ id: sourceId, paymentCity:this.paymentCity, paymentAddress:this.paymentAddress })
.then(() => {
this.clearForm();
});
}
}
我的 vuex 模块操作:
createSourceAndCustomer({ commit }, sourceData)
{
commit('Loader/SET_LOADER', { status:1, message: 'Añadiendo forma de pago...' }, { root: true });
return axios.post('/stripe/create-source-and-customer', sourceData)
.then((response) => {
commit('Loader/SET_LOADER', { status:2, message: response.data.message }, { root: true });
commit('CREATE_SOURCE_AND_CUSTOMER', response.data.customer);
},
(error) => {
commit('Loader/SET_LOADER', { status:3, errors: error, message: 'Oops, algo salio mal..' }, { root: true });
});
},
总而言之,我希望 clearForm 方法仅在 axios 调用成功时才发生,而不是总是触发。
【问题讨论】:
-
在您的代码中没有明显的原因应该在帖子返回之前返回 Promise。为了确保,暂时用新的
Promise(resolve => { setTimeout(() => resolve()), 1e4})替换您的方法内容。如果它立即返回,我们在您的控制器中遗漏了一些东西,并且它不包含在问题中。 minimal reproducible example 肯定会有所帮助。如果它按预期工作,那么您的axios(或特定呼叫)有问题。
标签: javascript php laravel vue.js