【问题标题】:Loading spinner when making Axios request发出 Axios 请求时加载微调器
【发布时间】:2019-05-08 00:48:46
【问题描述】:

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

【问题讨论】:

    标签: vue.js axios


    【解决方案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')
        })
    })
    

    【讨论】:

    • 我需要安装 2 个插件:“babel-polyfill”和“babel-plugin-transform-regenerator”,但还是不行。
    • 您需要使用 webpack 和 babel 或等效工具来转换 async/await 语法。 Vue cli 3 开箱即用。您在构建过程中使用什么?
    • 尝试使用 await 而不是从 vuex 操作返回。
    • 我已经关注了这个帖子stackoverflow.com/questions/46389267/…并配置了webpack.conf.js和.babelrc aoccrdingly
    • 我是这样做的:await this.$store.dispatch('createRide', formData) 但还是没有运气
    猜你喜欢
    • 2018-05-01
    • 2018-11-18
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2020-01-27
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多