javascript Vue.js - 无法读取未定义的属性“推送”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47549891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue.js - Cannot read property 'push' of undefined
提问by adam78
I have the following but I get error Cannot read property 'push' of undefined:
我有以下内容,但出现错误Cannot read property 'push' of undefined:
var vm = new Vue({
el: '#root',
data: {
posts: [],
newPost: {}
},
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
})
}
});
In my network tab in chrome dev tools I can see response.data is clearly an object:
在 Chrome 开发工具的网络选项卡中,我可以看到 response.data 显然是一个对象:
{
"id": 131,
"postContent": "<p>test</p>\n",
}
So why I'm i getting this error?
那么为什么我会收到此错误?
回答by IzumiSy
That's because thiscontext is assigned incorrectly which means that thisdoes not point on the Vue component. To solve this problem, you can use =>syntax which simply means a sophisticated way of this self = thisoutside of the target callback.
那是因为this上下文分配不正确,这意味着this它没有指向 Vue 组件。要解决这个问题,您可以使用=>语法,它仅表示this self = this目标回调之外的复杂方式。
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
回答by El Danielo
As IzumiSysaid, this very common problem when using axios or even setTimeout function. You can use es6 arrow synax, create temporary local variable with vm or bind it to the function.
正如IzumiSy所说,这是使用 axios 甚至 setTimeout 函数时非常常见的问题。您可以使用 es6 箭头 Synax,使用 vm 创建临时局部变量或将其绑定到函数。
ES6
ES6
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
Temporary variable
临时变量
createPost: function() {
let vm = this;
axios.post("api/posts/create", this.newPost).then(function (response) {
vm.posts.push(response.data);
})
}
Binding
捆绑
createPost: function() {
axios.post("api/posts/create", this.newPost).then(function (response) {
this.posts.push(response.data);
}.bind(this))
}

