如何在存储到vue数据对象后修改json数据

时间:2017-01-25 13:45:27

标签: json vuejs2

这是我的vue代码:

new Vue({
    el : '#root',

    data : {
        blog : []
    },

    created() {
       this.$http.get('https://jsonplaceholder.typicode.com/posts')
           .then(function(response) {
               // console.log(response.data)
               this.blog = response.data
           })
           .catch(function (error) {
               this.error = 'Error! Could not reach the API. ' + error
         })
   }

});

我的HTML代码是:

<div id="root" class="container">
        <ul v-for="post in blog">
            <li> {{ post.id }}  </li>
            <li>{{ post.userId }} </li>
            <li>{{ post.title }} </li>
        </ul>

    </div>

现在我可以很好地显示每个用户的名字,但我想修改一些内容,例如如果用户ID为1,则用户的名称将更改为“Smith”。 我试过这段代码:

mounted() {
        if (this.blog[0].userId == 1) {
                this.blog[0].userId = 'Smith'
          }
    }

但它显示了这个错误:

  

未捕获的TypeError:无法读取未定义的属性“userId”

如果我在方法中使用事件就可以了!怎么做?

在console.log之后(this.blog) enter image description here

在console.log(this.blog [0] .userId)之后,我得到:“1”

1 个答案:

答案 0 :(得分:2)

问题是您在博客数组中推送mounted()之前已完成response.data方法中的代码。这就是为什么它无法读取任何属性的原因。

您可以在获取数据后调用方法,在then()回调中调用方法以确保您在博客数组中有数据,而不是调用使用博客的方法:

methods: {
  changeNames() {
    if (this.blog[0].userId == 1) {
            this.blog[0].userId = 'Smith'
      }
  }      
},
created() {
  var self = this;
  this.$http.get('https://jsonplaceholder.typicode.com/posts')
  .then(function(response) {
    self.blog = response.data
    self.changeNames() // <----HERE
  })
  .catch(function (error) {
    console.log(error.statusText)
  })
}

以下是工作示例:jsFiddle

相关问题