Gor*_*tle 0 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);
});
})
Run Code Online (Sandbox Code Playgroud)
上面的代码输出: 似乎由于某种原因它无法获得ID 1,尽管没有下面的方法,相同的代码也获得ID 1。
found: {…}
found id: 2
TypeError: Cannot read property 'GetLikes' of undefined
Run Code Online (Sandbox Code Playgroud)
注释掉this.GetLikes(item.id)的输出:
found: {…}
found id: 2
found: {…}
found id: 1
Run Code Online (Sandbox Code Playgroud)
^以上显然可以获取所有项目,因此,如果我尝试对这些项目调用方法,为什么会得到未定义的信息?
下面的代码有效(获得正确的赞)。我在用户按下“赞”按钮时使用它,但是我首先还需要获得所有赞,这就是我上面想要做的。
Like(id) {
axios
.post("/like/" + id)
.then(response => {
this.GetLikes(id);
})
}
Run Code Online (Sandbox Code Playgroud)
我在这里想念什么?
this.data.forEach(function(item) {
console.log("found: ", item)
console.log("found id: ", item.id)
this.GetLikes(item.id);
});
Run Code Online (Sandbox Code Playgroud)
上面的代码为创建了一个新的作用域,this因此您获得property 'GetLikes' of undefined了forEach
你不会遇到这个问题
axios
.post("/like/" + id)
.then(response => {
this.GetLikes(id);
})
Run Code Online (Sandbox Code Playgroud)
因为ES6 箭头函数不绑定自己的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);
});
})
Run Code Online (Sandbox Code Playgroud)
不会this在forEach循环中绑定(请注意箭头功能)