1
votes

I am trying to build a front end web application in Vue. In one of my components, it renders a table and I am trying to use a child component to fill in some of the table data. The child component is in a for loop of the table row in the table body.

ParentComponent.vue:

<table> 
 <thead>
  <tr>
   <th>Header 1</th>
   <th>Header 2</th> 
   <th>Header 3</th>
   <th>Header 4</th>
  </tr> 
 </thead>
 <tbody>
  <tr v-for="looping">
   <td>Data</td>  
   <ChildComponent/>
  </tr>
 </tbody>
</table>

ChildComponent.vue:

<span> 
 <td>Data1</td> 
 <td>Data2</td>  
 <td>Data3</td> 
</span>

The problem I have is that when it makes the table, all the data in the component go into the same column. Is there a way to make the table data spread across the table to have the data be in their respective columns?

EDIT: the code provided above are inside template tags.

1
I think you should use v-slot. - sugars
use template instead of span in child component - tuhin47
The span tag cannot be the first child of tr. In addition, I suggest that you should encapsulate <tr>...</tr> as a whole in ChildComponent. - sugars

1 Answers

1
votes

Define ChildComponent first, content is for loop:

<template>
  <tr> 
    <td>{{ item.name }}</td> 
    <td>{{ item.age }}</td>  
  </tr>
</template>

<script>
export default {
  props: ["item"]
}
</script>

then write a fake data in parent component:

data() {
  return {
    list: [
      {
        name: "Jack",
        age: 32,
      },
      {
        name: "Rose",
        age: 21,
      },
      {
        name: "Bob",
        age: 45,
      },
    ]
  }
},

import child component

<script>
import ChildComponent from './ChildComponent.vue'
export default {
  components: {
    ChildComponent
  },
}
</script>

for the last, you can write the loop in the parent component:

<template>
  <table> 
    <thead>
      <tr>
        <th>Name</th>
        <th>Age</th> 
      </tr> 
    </thead>
    <tbody>
      <ChildComponent v-for="(item, index) in list" 
                      :key="index" 
                      :item="item" />
    </tbody>
  </table>
</template>