vuejs3primevue

Add increment count column in PrimeVue dataTable


I am using a primevue basic dataTable that works fine in VUE 3, composition api. I added a template column that is show to show each row incrementing by 1 and starting with 1. As you can see from the image below, the numbers are way off. Any ideas on how to fix?

enter image description here

Here's the sandbox link


Solution

  • You could add another property to your products array and display it in the table:

    <template>
      <div>
        <DataTable :value="productsWithRowNumber" responsiveLayout="scroll">
          <Column field="rowNumber" header="#"></Column>
          <Column field="code" header="Code"></Column>
          <Column field="name" header="Name"></Column>
          <Column field="category" header="Category"></Column>
          <Column field="quantity" header="Quantity"></Column>
        </DataTable>
      </div>
    </template>
    
    <script>
    import { ref, computed, onMounted } from "vue";
    import ProductService from "./service/ProductService";
    
    export default {
      setup() {
        onMounted(() => {
          productService.value
            .getProductsSmall()
            .then((data) => (products.value = data));
        });
    
        const products = ref([]);
        const productService = ref(new ProductService());
    
        const productsWithRowNumber = computed(() =>
          products.value.map((p, i) => ({ rowNumber: i + 1, ...p }))
        );
    
        return { productsWithRowNumber, productService };
      },
    };
    </script>         
    

    Be aware though, that this will only work properly if you do not change the sorting of the table.