Home > database >  how to add a column that numbers the table?
how to add a column that numbers the table?

Time:11-20

I use data-table with vuetify, You can see the final result I want in the image below. just add a column in the left side. I use data-table with vuetify, You can see the final result I want in the image below. just add a column in the left side.

<template>
  <v-card>
    <v-card-title>
      <v-text-field
        v-model="search"
        append-icon="mdi-magnify"
        label="Search"
        single-line
        hide-details
      ></v-text-field>
    </v-card-title>
    <v-data-table
      :headers="headers"
      :items="products.records"
      :search="search"
      :loading="isLoading"
    ></v-data-table>
  </v-card>
</template >

<script>
export default {
  name: "products",
  data() {
    return {
      search: "",
      headers: [
        {
          text: "Year",
          align: "start",
          filterable: true,
          value: "fields.year",
        },
        { text: "Item", value: "fields.item" },
        { text: "Element", value: "fields.element" },
        { text: "Value", value: "fields.value" },
        { text: "Unit", value: "fields.unit" },
        { text: "Area Code", value: "fields.area_code" },
        { text: "Area", value: "fields.area" },
      ],
      isLoading:true,
    };
  },
  created() {
    this.$store.dispatch("loadProducts");
  },
  computed: {
    products() {
      return this.$store.state.products;
      
    },
  },
  updated(){
    this.isLoading=false
  }
};
</script>

this is the result i want

CodePudding user response:

Simplest way I can think to do this is with the item.<name> slot which provides the row index which you can then easily display. For the <name> part of item.<name> just use a fake column name, e.g. item.num since it's not related to anything in your actual items data

<v-data-table
  :headers="headers"
  :items="products.records"
  :search="search"
  :loading="isLoading"
>
  <template v-slot:item.num="{ index }">
    {{ index   2 }}
  </template>
</v-data-table>

2 is added to the index so that the first row displays "2" since according to your image the header should display "1". The header value is set by just adding another object to the header array with text: '1', value: 'num':

headers: [
        { text: '1', value: 'num', sortable: false },
        {
          text: "Year",
          align: "start",
          filterable: true,
          value: "fields.year",
        },
        { text: "Item", value: "fields.item" },
        { text: "Element", value: "fields.element" },
        { text: "Value", value: "fields.value" },
        { text: "Unit", value: "fields.unit" },
        { text: "Area Code", value: "fields.area_code" },
        { text: "Area", value: "fields.area" },
      ]

codesandbox if you'd like to see a code example.

  • Related