[Vuejs]-Vue Js: How to add serial number column in Vue Data Table Component

3👍

There is no built-in way to do this, but you can achieve it by adding a computed property and use .map() method to add a new property to each items like sno, which stands for serial number. You can rename it anything you want.

computed: {
   itemsWithSno() {
      return this.desserts.map((d, index) => ({ ...d, sno: index + 1 }))
   }
},

Next, just add a new column in header array to map this new property like:

{
   text: 'Serial #',
   value: 'sno'
},

The value here needs to be exactly same as the new property name sno that you have added in the computed property.

Next, just update v-data-table items prop to use the computed property itemsWithSno instead of the original array like:

<v-data-table :headers="headers" :items="itemsWithSno">
</v-data-table>

That’s it.

Working Demo:

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'
        }
      ],
      desserts: [{
          name: 'Frozen Yogurt',
          calories: 159,
          fat: 6.0
        },
        {
          name: 'Ice cream sandwich',
          calories: 237,
          fat: 9.0
        },
        {
          name: 'Eclair',
          calories: 262,
          fat: 16.0
        },
        {
          name: 'Cupcake',
          calories: 305,
          fat: 3.7
        },
        {
          name: 'Gingerbread',
          calories: 356,
          fat: 16.0
        }
      ],
    }
  },
})
<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/font@5.x/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.js"></script>

<div id="app">
  <v-app>
    <v-main>
      <v-container>
        <v-data-table :headers="headers" :items="itemsWithSno" class="elevation-1">
        </v-data-table>
      </v-container>
    </v-main>
  </v-app>
</div>

Leave a comment