使用 Vue.js 异步/等待 axios 调用 [英] Async/await axios calls with Vue.js

查看:91
本文介绍了使用 Vue.js 异步/等待 axios 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置其中一个时遇到了一些麻烦.我的 Vue.js 应用程序中的值.我相信我要么没有正确理解 async axios 调用,要么没有正确理解 Vue.js 中的异步工作原理.

I'm having a little trouble setting one of my this. values within my Vue.js application. I believe I'm either not understanding async axios calls correctly, or how async works within Vue.js.

我有以下三种方法:

updateAvailability(availability) {
    if (availability == true) {
        this.showYourDetails();
    } else {
        this.showBookingDetails();
    }
},
checkAvailability: async function(event) {
    event.preventDefault();
    const availability = await this.handleAvailabilityRequest(event);
    this.loading = true;
    console.log(availability); //This evaluates to undefined
    const availabilityUpdate = await this.updateAvailability(availability);
    this.loading = false;
},
handleAvailabilityRequest: async function(event) {
    event.preventDefault();
    let valid = this.validateFieldsForAvailabilityRequest(); //Ignore this for this particular question, assume valid is always true

    if (valid) { // This is true
        let config = {
            headers: {
                "X-CSRFToken": this.csrfToken,
                "Content-Type": 'application/x-www-form-urlencoded',
            }
        }

        let formData = new FormData();
        let reservationTime = this.reservationHourSelected + ':' + this.reservationMinuteSelected;

        formData.set('type', 'availability_request');
        formData.set('session_name', this.sessionName);
        formData.set('reservation_party_size', this.reservationPartySize);
        formData.set('reservation_date', this.reservationDate);
        formData.set('reservation_time', reservationTime);

        await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response) {
            this.availabilityMessage = response.data.message;
        }).catch(function(error) {
            this.availabilityMessage = false;
            console.log(error);
        });
    }
    return this.availabilityMessage;
}

我的 response.data.message 正从我的框架作为 True/true 传回,但似乎我没有从 await this.handleAvailabilityRequest() 功能?当日志显示我想要的所有内容时,该帖子肯定会命中服务器 - 然后在 json 响应上下文中返回 message = true.

My response.data.message is being passed back from my framework as True/true but it seems I'm not returning anything from the await this.handleAvailabilityRequest() function? The post definitely hits the server as logging shows everything I want - then returns back message = true in json response context.

所以,我想……救命!除了等待承诺的问题之外,为什么这不起作用,完全傻眼了......

So, I guess ... help! Completely dumbfounded as to why this isn't working other than it being an issue with waiting for the promise...

推荐答案

问题出在这里:

await axios.post('{{ request_absolute_uri }}', formData, config).then(function(response){
  this.availabilityMessage = response.data.message;
}).catch(function (error) {
  this.availabilityMessage = false;
  console.log(error);
});

因为您使用的是成熟的function,所以.then 中的this 不引用实例化的对象.改用箭头函数,以便从外部作用域继承 this:

Because you're using a full-fledged function, your this inside the .then does not refer to the instantiated object. Use an arrow function instead so that the this is inherited from the outer scope:

await axios.post('{{ request_absolute_uri }}', formData, config)
.then((response) => {
  this.availabilityMessage = response.data.message;
}).catch((error) => {
  this.availabilityMessage = false;
  console.log(error);
});

这篇关于使用 Vue.js 异步/等待 axios 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆