【问题标题】:Using Vue component to fill table data (Vue only app)使用Vue组件填充表格数据(Vue only app)
【发布时间】:2020-12-12 00:48:21
【问题描述】:

我正在尝试在 Vue 中构建一个前端 Web 应用程序。在我的一个组件中,它呈现了一个表格,我正在尝试使用一个子组件来填充一些表格数据。子组件在表体中表行的for循环中。

父组件.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>

我遇到的问题是,当它制作表格时,组件中的所有数据都进入同一列。 有没有办法让表格数据分布在表格中以使数据位于各自的列中?

编辑:上面提供的代码在模板标签内。

【问题讨论】:

  • 我认为你应该使用v-slot
  • 在子组件中使用template 而不是span
  • span 标签不能是tr 的第一个子标签。另外,我建议你将&lt;tr&gt;...&lt;/tr&gt;作为一个整体封装在ChildComponent中。

标签: html vue.js vuejs2


【解决方案1】:

先定义ChildComponent,内容为for循环:

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

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

然后在父组件中写一个假数据:

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

导入子组件

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

最后,你可以在父组件中编写循环:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2020-08-19
    • 2020-08-25
    • 2018-10-24
    相关资源
    最近更新 更多