[Vuejs]-Insert value in html after axios get response

0👍

this in your function is not Vue instance.

You should use arrow function

var app2 = new Vue({
  el: '#app2',
  data: {
    message: null,
    post: [],
  },
  methods: {
    sendEmail: function () {
      var bodyFormData = new FormData();
      bodyFormData.set('email', this.message);
      axios({
        method: 'post',
        url: '/api/subsc/',
        data: bodyFormData,
      })
      .then((response) => {
        if (response.status == 201) {
          console.log(response);
          this.post = "Bla bla bla";
        }
      })
      .catch((error) => {
          this.post = error.response.data.email[0];
      });
    }
  }
})

or

var app2 = new Vue({
  el: '#app2',
  data: {
    message: null,
    post: [],
  },
  methods: {
    sendEmail: function () {
      var vm = this;
      var bodyFormData = new FormData();
      bodyFormData.set('email', this.message);
      axios({
        method: 'post',
        url: '/api/subsc/',
        data: bodyFormData,
      })
      .then(function (response) => {
        if (response.status == 201) {
          vm.post = "Bla bla bla";
        }
      })
      .catch(function (error) => {
          vm.post = error.response.data.email[0];
      });
    }
  }
})

Leave a comment