在axios中调用方法得到forEach

时间:2017-12-14 13:47:27

标签: javascript vue.js axios

我正在尝试调用位于GetLikes(item.id)forEach函数内的axios.get方法。我收到一条错误,说明TypeError: Cannot read property 'GetLikes' of undefined

如果我评论该方法,我可以看到我能够获取所有项目及其ID但是当我取消注释该方法时它不再有效。

axios
  .get("/api/endpoint")
  .then(response => {
    this.data = response.data;
    this.data.forEach(function(item) {
      console.log("found: ", item)
      console.log("found id: ", item.id)
      this.GetLikes(item.id);
    });
  })

以上代码输出: 似乎由于某些原因它无法获取id 1,尽管相同的代码只是在没有下面的方法的情况下获得id

found:  {…}
found id:  2
TypeError: Cannot read property 'GetLikes' of undefined

输出this.GetLikes(item.id)被注释掉:

found:  {…}
found id:  2
found:  {…}
found id:  1

^以上显然可以获取所有项目,如果我尝试在这些项目上调用方法,为什么会出现未定义的内容?

以下代码有效(获得正确的喜欢)。当用户按下时我会使用它,但是我还需要最初获得所有我想要做的喜欢。

Like(id) {
  axios
    .post("/like/" + id)
    .then(response => {
      this.GetLikes(id);
    })
}

我在这里缺少什么?

2 个答案:

答案 0 :(得分:3)

this.data.forEach(function(item) {
      console.log("found: ", item)
      console.log("found id: ", item.id)
      this.GetLikes(item.id);
    });

以上代码为this创建了一个新范围,因此property 'GetLikes' of undefined

的函数范围为forEach

你没有遇到这个问题
  axios
    .post("/like/" + id)
    .then(response => {
      this.GetLikes(id);
    })

因为ES6 arrow functions没有绑定自己的this

您可以尝试

axios
  .get("/api/endpoint")
  .then(response => {
    this.data = response.data;
    this.data.forEach((item) => {
      console.log("found: ", item)
      console.log("found id: ", item.id)
      this.GetLikes(item.id);
    });
  })

不会绑定this循环中的forEach(请注意箭头功能)

答案 1 :(得分:0)

使用forEach的箭头函数,因为它将此函数绑定到包含范围。

axios
  .get("/api/endpoint")
  .then(response => {
    this.data = response.data;
    this.data.forEach((item) => {
      console.log("found: ", item)
      console.log("found id: ", item.id)
      this.GetLikes(item.id);
    });
  })