【问题标题】:How can I create a Vue table component with column slots?如何创建带有列槽的 Vue 表格组件?
【发布时间】:2022-01-06 03:03:56
【问题描述】:

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

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

【问题讨论】:

    标签: javascript vue.js vuejs2 html-table


    【解决方案1】:

    有了这些数据,你只需要 2 个 Props、标签和数据。

    <!-- 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 结合使用作为表格的页眉或页脚(或其他选项,如搜索)。

    【讨论】:

    • 这是一种优雅的解决方法,感谢您的意见!
    猜你喜欢
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 2019-03-31
    • 1970-01-01
    • 2022-01-11
    • 2010-09-13
    • 2020-08-22
    相关资源
    最近更新 更多