Vue.js重新渲染排序数组

时间:2017-03-10 05:53:27

标签: arrays vue.js vuejs2 vue-component

我有一个基本的排序用户界面,可以根据一些值对评论进行排序:

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模板未重新呈现,因此agreedisagree不会更新。但是实际列表在单击每个排序选项卡时会呈现正确的排序,但列表中的每个注释都有错误的agreedisagree(原始排序数组的值)。知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

通过将key绑定到呈现的组件来解决:

<li is="comment" @delete="numComments -= 1" v-for="comment in sortedComments" :key="comment.id" :data="comment"></li>

参考:https://vuejs.org/v2/guide/list.html#key