'Update table when user clicked on pagination buttons

I have a vuetify table. Right now, I call API for all records and load all records into my table. I might not see the performance differences now because it's less than 1000. When I have 10,000,000 this might not work anymore. I need to only query for the first 10 on page loads, and my BE API already supports that. Then, I will make calls to API to get the next/previous 10 only when the user clicked on the pagination buttons.

enter image description here

data() {
    return {
        headers: [
            {
                text: 'Name',
                align: 'start',
                sortable: false,
                value: 'name',
                width: '20%'
            },
            { text: 'Link Count', value: 'count', width: '10%' },
            { text: 'URL', value: 'details', width: '50%' },
            { text: 'Actions', value: 'id', width: '20%' }
        ],
        items: []
    }
},

and I set this.items to the response from API below :

axios.defaults.headers['Content-Type'] = 'application/json'
axios
    .post(window.MTS_URL, vc_url_group)
    .then((response) => {
        this.items = response.data.groups           
    })

Can someone please get me started?



Solution 1:[1]

It's highly depends on your backend implementation, but there are some common points:

You should define v-data-table this way:

<v-data-table
  :headers="headers"
  :items="desserts"
  :items-per-page="10"
  :server-items-length="totalDesserts"
  :options.sync="options"
></v-data-table>

So you need to operate with three variables:

  • desserts as a [1..10] rows on your current page,
  • totalDesserts as a total amount of rows (10,000,000 in your case)
  • options as a synchronize point of your pagination

These variables comes from an example of official docs.

After that, in order to track user click on pagination buttons, you need to define a deep watcher (it should be deep in order to react to changes in nested props):

watch: {
  options: {
    handler() {
      this.getDessertsFromApi();
    },
    deep: true
  },
},

And then - your API call method:

methods: {
  async getDessertsFromApi() {
    this.loading = true;
    const { sortBy, sortDesc, page, itemsPerPage } = this.options;
    
    // Your axios call should be placed instead
    await this.simulateApiCall({
        size: itemsPerPage,
        page: page - 1,
      })
      .then((response) => {
        this.desserts = response.data.content;
        this.totalDesserts = response.data.totalElements;
      })
      .finally(() => {
        this.loading = false;
      });
  },
}

Test this at CodePen with simulated API calls.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Shkirkov