我在表单中有一个简单的按钮,我想在发出 Axios 请求时显示一个微调器。这是我的带有微调器的按钮(来自 loading.io)。
<form @submit.prevent="onSubmit" class="form-inline">
...
<button type="submit" class="btn btn-primary mb-5" id="loading" :disabled="loading">
<div class="lds-ring" v-if="loading"><div></div><div></div><div></div><div></div></div>
Submit
</button>
</form>
当 loading
为 true
时,我有条件地显示一个微调器。
我已经定义了 onSubmit
方法,但是我在请求之前发送一个 Action 并将 loading
更改为 true
并更改为 false
当请求完成但它不起作用时。你能解释一下为什么吗?
提交()
onSubmit () {
const formData = {
start_address: this.start_address,
destination_address: this.destination_address,
price_cents: this.price_cents,
date: this.date
}
this.loading = true
this.$store.dispatch('createRide', formData)
this.loading = false
}
创建乘车
createRide({ commit }, ride){
axios.post('/api/trips', ride)
.then(response => {
commit('addRide', response.data)
})
.then(response => {
commit('showSuccessAlert')
})
.catch(error => {
commit('showErrorAlert')
})
最佳答案
在发送 api 调用时,您需要等待 promise 解决,因为您已将加载属性立即设置为 false。尝试将方法更改为:
async onSubmit () {
const formData = {
start_address: this.start_address,
destination_address: this.destination_address,
price_cents: this.price_cents,
date: this.date
}
this.loading = true
// using await
await this.$store.dispatch('createRide', formData)
this.loading = false
// or without await
this.$store.dispatch('createRide', formData).then(() => {
this.loading = false
})
}
vuex store 操作也应该更新:
async createRide({ commit }, ride){
await axios.post('/api/trips', ride)
.then(response => {
commit('addRide', response.data)
})
.then(response => {
commit('showSuccessAlert')
})
.catch(error => {
commit('showErrorAlert')
})
})
关于vue.js - 发出 Axios 请求时加载微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649435/