JamesG
JamesG

Reputation: 1601

Vue.js. Cannot loop multiple table rows at the same time

I am trying to loop through an array and create 2 rows in a table.

Here is my desired output:

enter image description here

<tbody>
<tr>
  <td>col 1</td>
  <td>col 2</td>
  <td>col 3</td>
  <td>col 4</td>
</tr>
<tr>
  <td colspan="4">col 5 (This is a reall long 4 colspan row..................)</td>
</tr>

However, I seem to be getting stuck with doing this in Vue JS. If I am reading the docs correctly the way to loop through and repeat elements would be to do something like this:

<tr v-for="(data, index) in messages" :key="index">

However, that only accounts for the first tr.

How can I get that loop to account for 2 rows. I considered wrapping the tr in a div but that would not be semantically correct.

Edit: Using template tag.

<template v-for="data in messages">
      <tr>
        <td>col 1</td>
        <td>col 2</td>
        <td>col 3</td>
        <td>col 4</td>
      </tr>
      <tr>
        <td colspan="4"> col 5</td>
      </tr>
</template>

I am now getting two errors on both the tr tags that say

Elements in iteration expect to have 'v-bind:key' directives

When I add that to one, I get an error on the other. When I add it to both I get duplicate key error.

Upvotes: 2

Views: 1679

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

The official way would be to wrap your rows in a <template> tag.

https://v2.vuejs.org/v2/guide/list.html#v-for-on-a-lt-template-gt

//
var vm = new Vue({
  el: '#app',
  data() {
    return {
      messages: [{
        col1: '1',
        col2: '2',
        col3: '3',
        col4: '4',
        col5: '5'
      },{
        col1: 'a',
        col2: 'b',
        col3: 'c',
        col4: 'd',
        col5: 'e'
      }]
    }
  }
});
<div id="app">
  <table border="1">
    <tbody>
      <template v-for="(data, index) in messages" :key="index">
       <tr>
         <td>{{ data.col1 }}</td>
         <td>{{ data.col2 }}</td>
         <td>{{ data.col3 }}</td>
         <td>{{ data.col4 }}</td>
       </tr>
       <tr>
         <td colspan="4">{{ data.col5 }}</td> 
       </tr>
     </template>
    </tbody>
  </table>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.14/vue.min.js"></script>

Upvotes: 3

Related Questions