0

I have such code:

        <div class="col-md-4" id="app2">
          <div v-if="post && post.length">
              {{post}}
          </div>
          <input class="form-control" type="text" v-model="message" placeholder="Enter Email..." />
          <button class="btn btn-secondary" type="submit" v-on:click="sendEmail">Subscribe!</button>
        </div>

js:

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(function (response) {
        if (response.status == 201) {
          console.log(response);
          this.post = "Bla bla bla";
        }
      })
      .catch(function (error) {
          this.post = error.response.data.email[0];
      });
    }
  }
})

how can I insert a post in html when axios received a response? So, if response 201 then arbitrary string, if not 201, then error value?

Ihar
  • 189
  • 11

1 Answers1

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];
      });
    }
  }
})
ittus
  • 21,730
  • 5
  • 57
  • 57