【问题标题】:Vue.js - Cannot read property 'push' of undefined [duplicate]Vue.js - 无法读取未定义的属性“推送”[重复]
【发布时间】:2018-05-12 23:47:32
【问题描述】:

我有以下但我收到错误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.posts
  • 您的帖子数组变量在数据内部。所以我认为你应该使用 this.data.posts.push() 而不是 this.posts.push()
  • 刚刚在这里回答了....看看....stackoverflow.com/q/47549346/7814783
  • @VamsiKrishna 你是对的。我添加了=&gt; 语法,现在它可以工作了。谢谢。
  • @VamsiKrishna 为什么箭头功能在 IE11 中不起作用?我正在使用 webpack 并使用 "babel-preset-es2015": "^6.24.1", 和 ` "es6-promise": "^4.1.1",` 捆绑 javascript。

标签: javascript arrays json vue.js vuejs2


【解决方案1】:

这是因为 this 上下文分配不正确,这意味着 this 没有指向 Vue 组件。要解决这个问题,您可以使用=&gt; 语法,这意味着在目标回调之外使用this self = this 的复杂方式。

createPost: function() {
  axios.post("api/posts/create", this.newPost).then((response) => {
     this.posts.push(response.data);
  })
}

【讨论】:

    【解决方案2】:

    正如IzumiSy所说,这个问题在使用axios甚至setTimeout函数时很常见。您可以使用 es6 箭头语法,使用 vm 创建临时局部变量或将其绑定到函数。

    ES6

    createPost: function() {
     axios.post("api/posts/create", this.newPost).then((response) => {
        this.posts.push(response.data);
     })
    }
    

    临时变量

    createPost: function() {
    let vm = this;
      axios.post("api/posts/create", this.newPost).then(function (response) {
         vm.posts.push(response.data);
      })
    }
    

    绑定

    createPost: function() {
      axios.post("api/posts/create", this.newPost).then(function (response) {
         this.posts.push(response.data);
      }.bind(this))
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-01
      • 1970-01-01
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      相关资源
      最近更新 更多