Home > Software design >  v-for in array route // vuejs
v-for in array route // vuejs

Time:10-16

In the attached screen shot I want to get to the content. I'm trying to reach it with element.comments.content but doesn't work, see the code below:

<div class="fil-actualites-container">
  <div class="posts" v-for="(element, index) in postArray" :key="index">
    <p>{{ element.title }}</p>
    <p>{{ element.content }}</p>
    <p>{{ element.likes.length }}</p>
    <button @click="addLike(element._id)">Add Like</button>
    <br />
    <input
      type="text"
      v-model="contentComment"
      @keydown.enter="addComment(element._id)"
      placeholder="add Comment"
    />
    <p>{{ element.comments.content }}</p>
  </div>

screenshot

CodePudding user response:

comments is an array ([]) within the array of posts.

Therefore you need to loop over that to access the values within. I don't know your exact use case but something like this:

<div class="fil-actualites-container">
  <div class="posts" v-for="(element, index) in postArray" :key="index">
    <div v-for="(comment, i) in element.comments" :key="`comment-${i}`">
      <p>{{ comment.title }}</p>
      <p>{{ comment.content }}</p>
      <p>{{ comment.likes.length }}</p>
      <button @click="addLike(comment._id)">Add Like</button>
      <br />
      <input
        type="text"
        v-model="contentComment"
        @keydown.enter="addComment(comment._id)"
        placeholder="add Comment"
      />
      <p>{{ comment.content }}</p>
    </div>
  </div>

I have added another loop within your existing one to loop through the comments and access the values.

CodePudding user response:

The comments are related to the posts. A post can have several comments. If you now iterate through the posts, you will come to the key comments. Comments must also be looped through at this point. The oneToMany relationship is the reason why you have to include a comment loop within your post loop. This gives you access to every single comment. I hope this helps you without writing a lot of code.

  • Related