如何创建带有列槽的 Vue table 组件?

How can I create a Vue table component with column slots?

我目前正在处理一个相对较大的 Vue (Vue 2) 项目,该项目使用了大量 table,我想创建一个可重用的 table 组件,其中每一列都是一个子列组件/插槽。像这样:

<Table :data="data">
  <TableColumn field="id" label="ID" />
  <TableColumn field="name" label="Name" />
  <TableColumn field="date_created" label="Created" />
</Table>

const data = [
  { id: 1, name: 'Foo', date_created: '01.01.2021' },
  { id: 2, name: 'Bar', date_created: '01.01.2021' }
];

这又应该输出这个:

<table>
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Created</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Foo</td>
      <td>01.01.2021</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Bar</td>
      <td>01.01.2021</td>
    </tr>
  </tbody>
</table>

我们以前使用过 Buefy,但供应商规模变得不必要地大,因为我们只使用了组件功能的一小部分 - 所以我想创建一个轻量级的替代方案。

有了这些数据,您只需要 2 个道具、标签和数据。

<!-- Component -->
<table>
  <thead>
    <tr>
      <td v-for="(label, labelIndex) in labels" :key="labelIndex">
        {{ label.text }}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item, itemIndex) in data" :key="itemIndex">
      <td v-for="(label, labelIndex) in labels" :key="labelIndex">
        {{ item[label.field] }}
      </td>
    </tr>
  </tbody>
</table>
// Data and labels
const labels = [
  { text: ID, field: id },
  { text: Name, field: name },
  { text: Created, field: date_created },
]
const data = [
  { id: 1, name: 'Foo', date_created: '01.01.2021' },
  { id: 2, name: 'Bar', date_created: '01.01.2021' }
];
<table-component 
  :labels="labels" 
  :data="data"
>
</table-component>

如果您需要更复杂的东西,您可以将嵌套组件与 named slots 结合用于 table 的页眉或页脚(或搜索等其他选项)。