vue.js - 发出 Axios 请求时加载微调器

标签 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 方法,但是我在请求之前发送一个 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/

相关文章:

javascript - vue.js 入门不起作用

ruby-on-rails - Rails Webpacker 还是 Vue-CLI?

javascript - 在 Vue js 中将函数作为 prop 传递以获取数据

javascript - Python:发送 JSON 数据时使用 POST 请求的 FastAPI 错误 422

javascript - 如何使用 axios nuxt 模块进行基本身份验证

vue.js - Nuxtjs Axios onRequest() 未针对 asnycData 请求执行

Typescript 和 Vue.js - 属性在初始化之前使用

javascript - 路由中的 Vue JS 动态组件。处理加载和错误

javascript - 检查用户名或电话是否已存在(正面)

javascript - 下拉选择更改时更新状态 React