0

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.

3
  • I think you should use v-slot. Commented Aug 23, 2020 at 3:31
  • use template instead of span in child component Commented Aug 23, 2020 at 3:37
  • 2
    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. Commented Aug 23, 2020 at 3:39

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

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.