Skip to content
On this page

usePagination

Generic pagination control, handles all the pagination logic

State

The usePagination function exposes the following reactive state:

typescript
import { usePagination } from '@elonehoo/pistachio'

const { pageSize, total, currentPage, offset, lastPage } = usePagination()
import { usePagination } from '@elonehoo/pistachio'

const { pageSize, total, currentPage, offset, lastPage } = usePagination()
StateTypeDescription
pageSizenumberCurrent page size, allows to set the pageSize
totalnumberTotal elements
currentPagenumberCurrent page
offsetnumberCurrent page offset from the beginning
lastPagenumberLast page number

Methods

The usePagination function exposes the following methods:

typescript
import { usePagination } from '@elonehoo/pistachio'

const { next, prev, first, last } = usePagination()
import { usePagination } from '@elonehoo/pistachio'

const { next, prev, first, last } = usePagination()
SignatureDescription
next()Increments currentPage
prev()Decrements currentPage
first()Sets currentPage to 1
last()Sets currentPage = lastPage

Example

page 1 of 10

 

  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
vue
<script setup lang="ts">
import { computed, ref } from 'vue'
import { usePagination } from '@elonehoo/pistachio'

const arrayRef = ref(new Array(100).fill(1).map((_, i) => i))
// paginate array
const {
  currentPage,
  lastPage,
  next,
  prev,
  offset,
  pageSize
} = usePagination({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => arrayRef.value.length)
})

const result = computed(() => {
  const array = arrayRef.value
  if (!Array.isArray(array))
    return []
  return array.slice(offset.value, offset.value + pageSize.value)
})
</script>

<template>
  <div>
    <p>page {{ currentPage }} of {{ lastPage }}</p>
    <p>
      <button @click="prev">
        prev
      </button>
      <button @click="next">
        next
      </button>
    </p>
    <ul>
      <li v-for="n in result" :key="n">
        {{ n }}
      </li>
    </ul>
  </div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
import { usePagination } from '@elonehoo/pistachio'

const arrayRef = ref(new Array(100).fill(1).map((_, i) => i))
// paginate array
const {
  currentPage,
  lastPage,
  next,
  prev,
  offset,
  pageSize
} = usePagination({
  currentPage: 1,
  pageSize: 10,
  total: computed(() => arrayRef.value.length)
})

const result = computed(() => {
  const array = arrayRef.value
  if (!Array.isArray(array))
    return []
  return array.slice(offset.value, offset.value + pageSize.value)
})
</script>

<template>
  <div>
    <p>page {{ currentPage }} of {{ lastPage }}</p>
    <p>
      <button @click="prev">
        prev
      </button>
      <button @click="next">
        next
      </button>
    </p>
    <ul>
      <li v-for="n in result" :key="n">
        {{ n }}
      </li>
    </ul>
  </div>
</template>

Released under the MIT License.