带加载程序的Vuetify按钮继续处于加载状态

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

enter image description here

<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;                   
                });
        }
    }
})

难道我做错了什么 ?

评论
  • 胡了~
    胡了~ 回复

    正确的解决方案是:

    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;                   
    });
    

    Know that, if you use function () {}, your scope will change:

    myFunction()
      .then(function () {
        // myfunction() scope
        // this = myFunction prototype
      })
    
    myFunction()
      .then(() => {
        // stay in current scope
      })
    
  • wsed
    wsed 回复

    You should use an arrow function ()=> to get access to the component instance and use this :

    .then((response)=> {
                        this.loading = false;               
                        console.log(response.data);
                    })
                    .catch( (response)=> {
                        this.loading = false;                   
                    });
    

    由于出现类似以下的错误:

    无法读取未定义的属性“加载”