Async/await axios calls with Vue.js

后端 未结 2 1130
天涯浪人
天涯浪人 2021-02-07 21:16

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

2条回答
  •  醉酒成梦
    2021-02-07 21:33

    The problem is here:

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

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

提交回复
热议问题