我有以下内容,但出现错误 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);
})
}
});
在 Chrome 开发工具的网络选项卡中,我可以看到 response.data 显然是一个对象:
{
"id": 131,
"postContent": "<p>test</p>\n",
}
那么为什么我会收到此错误?
最佳答案
这是因为 this
上下文分配不正确,这意味着 this
没有指向 Vue 组件。要解决这个问题,您可以使用 =>
语法,它只是意味着在目标回调之外使用 this self = this
的复杂方式。
createPost: function() {
axios.post("api/posts/create", this.newPost).then((response) => {
this.posts.push(response.data);
})
}
关于javascript - Vue.js - 无法读取未定义的属性 'push',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549891/