Good day,
In trying to learn VueJS I wanted to make a generic Vuetify Data Table that could receive an array of objects with n properties, where n is unknown.
Every example and article I’ve found about using these tables hard-codes the object properties into their headers and items slots, something like this:
<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>
Which is fine if there is 1 or 2 datasets. But what if to load one of 100 different datasets into my data-table? Do I really need 100 different “foo-table” components with hard-coded values?
How do I handle the template interpolation that would allow me to reuse a single data-table component that could handle data like:
items: [{ name: ‘foo’, age: 100, occupation: ‘retired’ }, …]
and
items: [{ seq: ‘1234’, data: ‘XYZ’, flag: ‘N’, operator: ‘someone’, }, …]
and correctly v-for each <tr> by the item and the <td> by each item parameter as dictated by the headers (where item[n][header[i].value])?
What I’ve done so far.
I’ve spent a fair amount of time on this and the best I came up with is something like the following:
<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>
But it doesn’t work because it’s producing items.length-times as many rows because I think the items slot is already implicitly doing a v-for inside of it, making my <tr v-for …> redundant.
Does anyone have any better ideas on how I can accomplish a generic data-table?
Solution :
I think the items slot is already implicitly doing a v-for inside of
it.
That’s correct, and you only one loop for each row:
<template slot=”items” slot-scope=”props”>
<td v-for=”header in headers”>{ props.item[header.value] }</td>
</template>
See this adapted pen from vuetify site. https://codepen.io/anon/pen/daQbrE?&editable=true&editors=101