Javascript 如何反应式更新vue.js循环中的阵列?
在像Vue.js应用程序这样的博客中,当新评论成功发布到服务器时,我想用新评论更新帖子的评论列表 这是我的密码:Javascript 如何反应式更新vue.js循环中的阵列?,javascript,vue.js,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" clas
<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>
尽管我收到了更新后的注释列表,但仍会呈现空结果。如何修复此问题?正如@blaz在上面的评论中指出的那样,错误似乎来自
$set
方法调用中的键入错误,因为属性应该是复数注释
而不是注释您可以发布从服务器获得的json
响应吗?是否应该是此。$set(发表“评论”,res.data.comments)
和评论的复数形式?@VladNeacsu你是对的。这是我愚蠢的错误。请回答,我会接受。
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);
});
}