【问题标题】:VueJS / Vuetify - Possible to dynamically load a data table without having to hard-code the columns?VueJS / Vuetify - 可以动态加载数据表而无需对列进行硬编码?
【发布时间】:2024-01-23 04:35:01
【问题描述】:

早安,

在尝试学习 VueJS 时,我想创建一个通用的 Vuetify Data Table,它可以接收具有 n 属性的对象数组,其中 n 是未知的。

我发现的每个关于使用这些表的示例和文章都将对象属性硬编码到它们的 headersitems 插槽中,如下所示:

<template slot="items" slot-scope="props">
  <td>{{ props.item.name }}</td>
  <td class="text-xs-right">{{ props.item.calories }}</td>
  <td class="text-xs-right">{{ props.item.fat }}</td>
  <td class="text-xs-right">{{ props.item.carbs }}</td>
  <td class="text-xs-right">{{ props.item.protein }}</td>
</template>

如果我有 1 或 2 个数据集,这很好。但是,如果我想将 100 个不同的数据集之一加载到我的数据表中怎么办?我真的需要 100 个具有硬编码值的不同“foo-table”组件吗?

如何处理允许我重用可以处理数据的单个数据表组件的模板插值:

items: [{ name: 'foo', age: 100, occupation: 'retired' }, ...]

items: [{ seq: '1234', data: 'XYZ', flag: 'N', operator: 'someone',  }, ...]

并且正确地v-for每个&lt;tr&gt;由项目和&lt;td&gt;由每个项目参数指定由headers(其中item[n][header[i].value])?


到目前为止我做了什么。

我在这方面花费了相当多的时间,我想出的最好的方法如下:

<template slot='items' slot-scope='props'>
  <tr v-for='(item, i_index) in items' :key='i_index'>
    <td v-for='(header, h_index) in headers' :key='h_index'>
      {{ items[i_index][header.value] }}
    </td>
  </tr>
</template>

但它不起作用,因为它产生了 items.length-times 的行数,因为我认为 items slot 已经隐式地在其中执行 v-for ,使我的 &lt;tr v-for ...&gt; 多余。


有没有人对如何完成通用数据表有更好的想法?

【问题讨论】:

    标签: vue.js vuetify.js


    【解决方案1】:

    我认为 items 插槽已经隐式地在里面做了一个 v-for 它。

    没错,每一行只有一个循环:

    <template slot="items" slot-scope="props">
      <td v-for="header in headers">{{ props.item[header.value] }}</td>
    </template>
    

    从 vuetify 网站查看这个改编的笔。 https://codepen.io/anon/pen/daQbrE?&editable=true&editors=101

    【讨论】:

    • 太棒了!做到了。非常感谢。
    最近更新 更多