我在表单中有一个简单的按钮,当我提出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
方法,但在其中我调度了一个操作,并将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')
})
答案 0 :(得分:1)
在分派api调用时,您需要等待promise解析,因为您已编写了它,将loading属性立即设置为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存储操作也应更新:
async createRide({ commit }, ride){
await axios.post('/api/trips', ride)
.then(response => {
commit('addRide', response.data)
})
.then(response => {
commit('showSuccessAlert')
})
.catch(error => {
commit('showErrorAlert')
})
})