我有一个基本的排序用户界面,可以根据一些值对评论进行排序:
CommentsSection
模板的一部分:
<div v-if="numComments" class="tabs d-flex">
<span class="text-muted">Sort by:</span>
<div class="tab" :class="{active: tab === 0}" @click="sortComments(0)">Rating</div>
<div class="tab" :class="{active: tab === 1}" @click="sortComments(1)">Newest</div>
<div class="tab" :class="{active: tab === 2}" @click="sortComments(2)">Oldest</div>
</div>
<ul v-if="numComments" class="comments-list">
<li is="comment" @delete="numComments -= 1" v-for="comment in sortedComments" :data="comment"></li>
</ul>
CommentsSection
:
export default {
name: 'comments-section',
components: {
CommentForm,
Comment
},
props: ['comments', 'submissionId'],
data() {
return {
tab: 0,
numComments: this.comments.length,
sortedComments: this.comments.slice()
}
},
created() {
this.sortComments();
},
methods: {
sortComments(type = 0) {
this.tab = type;
if (type === 0) {
this.sortedComments.sort((a, b) => b.rating - a.rating);
} else if (type === 1) {
this.sortedComments.sort((a, b) => moment(b.create_time).unix() - moment(a.create_time).unix());
} else {
this.sortedComments.sort((a, b) => moment(a.create_time).unix() - moment(b.create_time).unix());
}
},
...
}
...
}
CommentSingle
(在列表中呈现的组件):
export default {
name: 'comment-single',
props: ['data'],
data() {
return {
agree: this.data.rated === 1,
disagree: this.data.rated === -1
}
}
...
}
CommentSingle
模板未重新呈现,因此agree
和disagree
不会更新。但是实际列表在单击每个排序选项卡时会呈现正确的排序,但列表中的每个注释都有错误的agree
和disagree
(原始排序数组的值)。知道如何解决这个问题吗?
答案 0 :(得分:1)
通过将key
绑定到呈现的组件来解决:
<li is="comment" @delete="numComments -= 1" v-for="comment in sortedComments" :key="comment.id" :data="comment"></li>