我正在使用<v-data-table>
组件在我的应用程序中显示数据表。有什么方法可以在此数据表中添加序列号列。从1到我的articles数组的长度。
如果有任何ID的文章排在第一位,则应该从1开始。
没有内置方法可以执行此操作,但是您可以通过添加计算属性并使用.map()
方法向每个项目(例如sno
)添加新属性来实现,该属性代表序列号。您可以根据需要将其重命名。
computed: {
itemsWithSno() {
return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
}
},
接下来,只需在标题数组中添加一个新列即可映射此新属性,如:
{
text: 'Serial #',
value: 'sno'
},
这里的值必须与您在计算属性中添加的值完全相同。
正在工作的演示:
new Vue({
el: '#app',
vuetify: new Vuetify(),
computed: {
itemsWithSno() {
return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
}
},
data() {
return {
headers: [{
text: 'Serial #',
value: 'sno'
},
{
text: 'Dessert (100g serving)',
align: 'start',
sortable: false,
value: 'name',
},
{
text: 'Calories',
value: 'calories'
},
{
text: 'Fat (g)',
value: 'fat'
},
{
text: 'Carbs (g)',
value: 'carbs'
},
{
text: 'Protein (g)',
value: 'protein'
},
{
text: 'Iron (%)',
value: 'iron'
},
],
desserts: [{
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
carbs: 24,
protein: 4.0,
iron: '1%',
},
{
name: 'Ice cream sandwich',
calories: 237,
fat: 9.0,
carbs: 37,
protein: 4.3,
iron: '1%',
},
{
name: 'Eclair',
calories: 262,
fat: 16.0,
carbs: 23,
protein: 6.0,
iron: '7%',
},
{
name: 'Cupcake',
calories: 305,
fat: 3.7,
carbs: 67,
protein: 4.3,
iron: '8%',
},
{
name: 'Gingerbread',
calories: 356,
fat: 16.0,
carbs: 49,
protein: 3.9,
iron: '16%',
},
{
name: 'Jelly bean',
calories: 375,
fat: 0.0,
carbs: 94,
protein: 0.0,
iron: '0%',
},
{
name: 'Lollipop',
calories: 392,
fat: 0.2,
carbs: 98,
protein: 0,
iron: '2%',
},
{
name: 'Honeycomb',
calories: 408,
fat: 3.2,
carbs: 87,
protein: 6.5,
iron: '45%',
},
{
name: 'Donut',
calories: 452,
fat: 25.0,
carbs: 51,
protein: 4.9,
iron: '22%',
},
{
name: 'KitKat',
calories: 518,
fat: 26.0,
carbs: 65,
protein: 7,
iron: '6%',
},
],
}
},
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<div id="app">
<v-app>
<v-content>
<v-container>
<v-data-table :headers="headers" :items="itemsWithSno" :items-per-page="5" class="elevation-1">
</v-data-table>
</v-container>
</v-content>
</v-app>
</div>