首页 > 解决方案 > 带有加载程序的 Vuetify 按钮继续处于加载状态

问题描述

我用按钮加载器制作了简单的 vuetify 登录表单。但是通过 axios 发送 POST 请求后,按钮不会恢复到正常状态。它继续加载状态。

在此处输入图像描述

<v-btn color="primary" block x-large depressed :loading="loading" :disabled="loading" color="secondary" @click="submit">Sign In</v-btn>
new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data() {
        return {
            email: 'admin@example.com',
            password: '',
            loading: false
        }
    },
    methods: {
        submit() {
            this.loading = true;
            axios({
                method: 'post',
                url: remote_url,
                data: {
                    username: this.email,
                    password: this.password
                }
            })
                .then(function (response) {
                    this.loading = false;               
                    console.log(response.data);
                })
                .catch(function (response) {
                    this.loading = false;                   
                });
        }
    }
})

难道我做错了什么 ?

标签: javascriptvue.jsvuejs2vuetify.js

解决方案


正确的解决方案是:

this.loading = true;
axios({
  method: 'post',
  url: remote_url,
  data: {
    username: this.email,
    password: this.password
  }
})
.then((response) => {            
  // response handler
})
.catch((error) => {
  // error handler
})
.finally(() => {
  this.loading = false;                   
});

知道,如果你使用function () {},你的范围将会改变:

myFunction()
  .then(function () {
    // myfunction() scope
    // this = myFunction prototype
  })

myFunction()
  .then(() => {
    // stay in current scope
  })

推荐阅读