0

I have a basic sorting UI to sort comments based on some values:

Part of CommentsSection template:

<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 (component being rendered in list):

export default {
    name: 'comment-single',
    props: ['data'],
    data() {
        return {
            agree: this.data.rated === 1,
            disagree: this.data.rated === -1
        }
    }
   ...
}

The CommentSingle template is not being re-rendered so agree and disagree don't update. But the actual list does render the proper sort when clicking each sorting tab, but each comment in the list has the wrong agree and disagree (the original sorted array's values). Any idea how to fix this?

1
  • possible to create a fiddle of it? Commented Mar 10, 2017 at 6:03

1 Answer 1

1

Solved by binding a key to the rendered component:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.