[Vuejs]-Using v-for with multiple keys

3👍

Solution for only one depth

I would organize the data differently and use a different approach.
The data would be more coherent if you have an object list with your parent comments and your parent object has a child comment object list.

Example:

   comments = [{
               id: 1,
               username: "John SMITH",
               timestamp: "9999-12-31 23:59:59.999999",
               text: "This is a parent comment",
               commentChild: [{
                               id: 2,
                               username: "Angela SMITH",
                               timestamp: "9999-12-31 23:59:59.999999",
                               text: "This is a Child comment",
                              },]
               },]

With this it is easy to make a first for loop to browse your parents and within it, a for loop to browse the children, if there are any.

<template>
  <div>
    <template v-for="comment in comments" :key="comment.id">
      <div>Your parent comment data</div>
      <template v-for="commentChild in comment.commentChild" :key="commentChild.id">
        <div>Your child comment data</div>
      </template>
    </template>
  </div>
</template>

Solution for infinite depth

To handle an unknown depth, you must have a recursive component and a parent component that will initiate the first call.

This is what it can do:

Comment Interface

interface Comment {
  id: number;
  comments?: Comment[];
// And all data you want
}

Component Parent (initial call):

<template>
//Only here for call the recursive component
// Take your list of comments
  <MyCommentsRecursiveComponent :comments="comments"></Test>
</template>

MyCommentsRecursiveComponent:

<script setup lang="ts">

defineProps<{ comments: Comment[] }>();

</script>

<template>
  <div>
    <template v-for="(actualComment, index) in comments">
      <p>{{ actualComment.id }}</p>
      <div>
        // Component call himself / Recursive
        <MyCommentsRecursiveComponent
          v-if="actualComment.comments"
          :comments="actualComment.comments"
        ></MyCommentsRecursiveComponent>
      </div>
    </template>
  </div>
</template>

Leave a comment