javascript - Vue.js - 无法读取未定义的属性 'push'

标签 javascript arrays json vue.js vuejs2

我有以下内容,但出现错误 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/

相关文章:

javascript - 在 angular.js 应用程序中使用 jQuery 插件 (flipclock)

javascript - 删除 node.js 数组中具有相同开头的项

arrays - 在一个数组中使用解析服务器加载数据

sql - 有没有办法在 HiveQL 中对数组使用 like 运算符?

javascript - 在浏览器中使用 Node 模块

PHP 未收到 jQuery AJAX 发送的 JSON

javascript - 我的 PHP URL 不会重定向

javascript - JSON.parse 提示 "unexpected end of data"

javascript - 使用 jquery grep 过滤具有值数组的 json 对象

javascript - 覆盖 iframe 内容 css