在axios获得响应后,在html中插入值

时间:2018-05-21 12:18:47

标签: vue.js axios

我有这样的代码:

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

当axios收到回复时如何在html中插入帖子?那么,如果响应201然后是任意字符串,如果不是201,那么错误值?

1 个答案:

答案 0 :(得分:0)

您函数中的

Vue不是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]; }); } } }) 实例。

你应该使用箭头功能

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

Player_details