我在我的Vue.js应用程序中设置一个this的值时遇到了一些麻烦。我认为我可能没有正确理解异步axios调用,或者不知道在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。
所以, 我猜... 帮帮我!除了等待承诺的问题之外,我完全不知道为什么它不起作用...
.bind(this)
。 - Thoomas