发出Axios请求时加载微调器

时间:2018-12-06 10:34:40

标签: vue.js axios

我在表单中有一个简单的按钮,当我提出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>

有一个微调框,当loadingtrue时有条件显示。

我已经定义了onSubmit方法,但在其中我调度了一个操作,并将loading更改为请求之前的true,并在请求完成后更改为false,但是没有。工作。您能解释一下为什么吗?

onSubmit()

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
      }

create_ride

createRide({ commit }, ride){
    axios.post('/api/trips', ride)
      .then(response => {
        commit('addRide', response.data)
      })
      .then(response => {
        commit('showSuccessAlert')
      })
      .catch(error => {
        commit('showErrorAlert')
      })

1 个答案:

答案 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')
    })
})
相关问题