posva / unplugin-vue-router

Next Generation file based typed routing for Vue Router
https://uvr.esm.is
MIT License
1.7k stars 82 forks source link

How to do pagination? #498

Closed Shujee closed 2 months ago

Shujee commented 2 months ago

How are Data Loaders supposed to be used in the context of pagination? So for example, I'm using Vuetify's Server-side Data Tables, which provide support for server-side pagination, but the page variable is sent in query string rather than as a route parameter. How am I supposed to pass page=N part to my data loader?

Here is my page:

<template>
    <v-data-table-server
      v-model:page="page"
      :headers="headers" item-value="name" :items="items?.data" :items-length="items?.meta?.total??0"
      :loading="loading" @update:options="reloadMe"
    />
  </v-row>
</template>

<script lang="ts">
  //ESLint wants me to keep all imports in non-setup script block
  import { useBatchData } from '@/composables/useBatchData'
  import { AxiosErrorEx, Batch, DataTableHeader } from '@/composables/types'
  import { showConfirmKey, showSnackKey, snackTextKey } from '@/InjectionKeys'
  import { ref } from 'vue'
  import IconButtonWithTooltip from '@/components/IconButtonWithTooltip.vue'
  import useRequestHandler from '@/composables/useRequestHandler'
  export { useBatchData }
</script>

<script setup lang="ts">
  const router = useRouter()

  const page = ref<number>(1)

  const headers = ref<DataTableHeader[]>([
  ...
  ])

  const {
    data: items, 
    isLoading: loading, 
    error, 
    reload, 
  } = useBatchData()

  const reloadMe = (data: { page: number, itemsPerPage: number, sortBy: string }) => {
    //Tried this; doesn't work
    // const route = useRoute()
    // const rcopy = Object.assign({}, route)
    // route.query = { page: data.page.toString() }

    reload()
  }
</script>

and here is my Data Loader:

import useRequestHandler from '@/composables/useRequestHandler'
import { defineBasicLoader } from 'unplugin-vue-router/data-loaders/basic'
import { Batch, PagedResponse } from '@/composables/types'

export const useBatchData = defineBasicLoader('/batches/', async to => {
  const { get } = useRequestHandler()
  const batches = await get<PagedResponse<Batch>>('batch', {
    page: to.query.page,
  })

  return batches
})