如何以响应方式更新vue.js循环中的数组?

时间:2019-01-16 09:54:33

标签: javascript vue.js

在类似博客的Vue.js应用程序中,当新评论成功发布到服务器时,我想用新评论更新帖子的评论列表。

这是我的代码:

<div v-for="(post, index) in posts" :key="index" >  
    <div>{{post.body}}</div>
    <div class="comments">
        <ul v-for="(c, j) in post.comments" :key="j" class="comment">                      
          <li>{{c.user_id}} : {{c.body}} </li>
        </ul>    
    </div>

     <div>                  
        <input type="text" v-on:keyup.enter="submitComment(post)" v-model="post.comment" placeholder=" Add your comment" />                  
     </div>
</div>

方法:

  submitComment(post) {
    const formData = new FormData();
    formData.append('token', this.token);
    formData.append('pid', post.id);
    formData.append('body', post.comment);
    axios.post(this.BASE_URL + "/api/comment", formData)
    .then( (res)=> {
      console.log('Updated comments are', res.data.comments);
      this.$set(post, 'comment', res.data.comments) ; //Here is the problem
    })
    .catch( error => {  
      console.log(error);
    });
  }

尽管我收到了更新的评论列表,但呈现了空白结果。我该如何解决?

1 个答案:

答案 0 :(得分:1)

正如@blaz在上面的注释中指出的那样,错误似乎来自$set方法调用中的错字,因为该属性应为复数comments而不是comment < / p>