Custom Vuetify V3 Pagination To Support RouterLink/NuxtLink To

Dec 28, 2022
<script setup>import { VPagination } from 'vuetify/components/VPagination'const props = defineProps({  page: Number,  length: Number,  totalVisible: Number,  to: Function})const range = (start, stop, step = 1) =>  Array(Math.ceil((stop - start) / step)).fill(start).map((x, y) => x + y * step)let totalVisible = props.totalVisible - 2if (totalVisible < 0)  totalVisible = 3let total = Math.floor(totalVisible/2)let start = props.page - totalif (start <= 0) {  total = 0  start = 1}total = totalVisible - totallet end = props.page + totalif (end > props.length) {  end = props.length  start -= total  if (start <= 0)    start = 1}let pages = range(start, end)if (pages[0] != 1) {  pages.unshift(1)  if (pages[1] != 2) {    pages.splice(1, 0, 0);  }}if (pages[pages.length - 1] != props.length) {  pages.push(props.length)  if (pages[pages.length - 2] != props.length-1) {    pages.splice(pages.length-1, 0, 0);  }}</script><template>  <!-- need this to trigger dynamic import due to treeshaking, or import VPagination.sass -->  <v-pagination v-show="false" />  <nav class="v-pagination" role="navigation" aria-label="Pagination Navigation">    <ul class="v-pagination__list">      <li class="v-pagination__prev">        <v-btn :disabled="page == 1" icon  variant="text" :to="page != 1 ? to(page - 1) : {}" >         «        </v-btn>      </li>      <li v-for="page in pages" :key="page" class="v-pagination__item">        <v-btn :disabled="page == 0" icon  variant="tonal" :to="page > 0 ? to(page) : {}" >          {{ page == 0 ? '...' : page }}        </v-btn>      </li>      <li class="v-pagination__next">        <v-btn :disabled="page == length" icon  variant="text" :to="page != length ? to(page + 1) : {}" >         »        </v-btn>      </li>    </ul>  </nav></template><style type="scss">// @import 'vuetify/lib/components/VPagination/VPagination.sass';</style>

Usage

<script setup>const page = 1const itemSize = 95const pageSize = 10const pagination = computed(() => {  return {    length: Math.ceil(itemSize / pageSize),    page: page  }})function to(page) {  if (page == 1)    return '/tutorials'  return `/tutorials/page/${page}`}</script><template>  <div>    <div class="flex justify-start" v-if="pagination.length > 1">      <Pagination :page="pagination.page" :length="pagination.length" :total-visible="5" :to="to" />    </div>  </div></template>

Sample

Vuetify Pagination

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.