VueJS和Axios-如何在发布请求中访问数据

时间:2020-07-15 17:30:05

标签: javascript vue.js axios this

我有这样的数据:

  data: () => ({
    input: {
      username: "",
      password: ""
    }
  }),

并发出这样的发布请求:

loggin_in() {
  if (this.input.username != "" && this.input.password != "") {
    console.log(this.input.username);
    axios
      .post("http://localhost:5000/login", {
        email: this.input.username,
        password: this.input.password
      })
      .then(function(data) {
        console.log(data);
      })
      .catch(function(error) {
        console.log(this.input.username);
      });
  }
}

记录第一个this.input.username是可行的,但是在那之后,我不知道如何访问数据。 this似乎未定义。

Uncaught (in promise) TypeError: Cannot read property 'input' of undefined

我不知道为什么this的上下文在这里更改,并且不了解如何访问我的数据。有人可以向我解释发生了什么事并对此提供帮助吗?

1 个答案:

答案 0 :(得分:2)

在回调中,您必须将此绑定或使用箭头函数:

  .then(function(data) {
         console.log(data);
      })

  .then((data) => {
    console.log(data);
    console.log(this);
  })