0

Looping data from an array. The problem is that the loop creates 3 empty tables, guessing it's because im calling item. 3 times. If I want the data from the array without Vue creating empty tables, how should I display the data? Been trying to use {{users.firstname}} without the v-for loop but doesn't seem to work.

<table v-for="item in users">
        <tbody>
          <tr>
            <td>{{ item.username }}</td>
          </tr>
          <tr>
            <td>{{ item.firstname }}</td>
          </tr>
          <tr>
            <td>{{ item.lastname }}</td>
          </tr>
       </tbody>
      </table>

Solved using <template v-for="item in users" v-if="item.username && item.firstname && item.lastname">. No extra elements are printed out.

3
  • Move v-for directive from table element to td Commented Nov 21, 2017 at 19:39
  • Do you want 3 tables, one per item? Or do you want 3 rows per item? I'm not sure what your expected output is. Commented Nov 21, 2017 at 19:40
  • I want 1 table with 3 rows displaying different data on every row. Username Firstname and Lastname Commented Nov 21, 2017 at 19:47

1 Answer 1

3

If you want to create 3 rows per user, use a <template> tag to group them, and use v-for on that template:

  <table>
    <tbody>
      <template v-for="item in users">
        <tr>
          <td>{{ item.username }}</td>
        </tr>
        <tr>
          <td>{{ item.firstname }}</td>
        </tr>
        <tr>
          <td>{{ item.lastname }}</td>
        </tr>
     </template>
   </tbody>
  </table>

Have a look at this fiddle for an example: https://jsfiddle.net/nfa43bhq/

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

2 Comments

Hmm still adds empty rows, creates empty rows both above and below the rows that are actually displaying data.
Works fine with the hardcoded data in your fiddle, problem is i'm getting data from an API that I put in the array, when i loop through, it creates empty elements for some reason.

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.