Search code examples
javascriptvue.jsvue-cli

v-for in array route // vuejs


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


Solution

  • 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.