Files
web/app/components/datatable/Pagination.vue
2026-06-05 13:36:14 +07:00

94 lines
2.3 KiB
Vue

<template>
<nav
class="pagination mx-0"
role="navigation"
aria-label="pagination"
>
<ul
class="pagination-list"
v-if="pageInfo"
>
<li v-for="v in pageInfo">
<a
v-if="currentPage === v"
class="pagination-link is-current has-background-primary has-text-white"
:aria-label="`Page ${v}`"
aria-current="page"
>{{ v }}</a
>
<a
v-else
class="pagination-link"
:aria-label="`Goto page ${v}`"
@click="changePage(v)"
>{{ v }}</a
>
</li>
<a
@click="previous"
class="pagination-previous ml-5"
>
<Icon name="material-symbols:arrow-back-ios-new-rounded" />
</a>
<a
@click="next"
class="pagination-next"
>
<Icon name="material-symbols:arrow-forward-ios-rounded" />
</a>
</ul>
</nav>
</template>
<script setup>
const props = defineProps({
data: Array,
perPage: Number,
});
const emit = defineEmits(["changepage"]);
let currentPage = 1;
let totalRows = props.data.length;
let lastPage = parseInt(totalRows / props.perPage);
if (lastPage * props.perPage < totalRows) lastPage += 1;
const pageInfo = ref();
function pages(current_page, last_page, onSides = 2) {
// pages
let pages = [];
// Loop through
for (let i = 1; i <= last_page; i++) {
// Define offset
let offset = i == 1 || last_page ? onSides + 1 : onSides;
// If added
if (i == 1 || (current_page - offset <= i && current_page + offset >= i) || i == current_page || i == last_page) {
pages.push(i);
} else if (i == current_page - (offset + 1) || i == current_page + (offset + 1)) {
pages.push("...");
}
}
return pages;
}
function changePage(page) {
if (page === "...") return;
currentPage = page;
pageInfo.value = pages(page, lastPage, 2);
emit("changepage", page);
}
pageInfo.value = pages(1, lastPage, 2);
watch(
() => props.data,
() => {
totalRows = props.data.length;
lastPage = parseInt(totalRows / props.perPage);
if (lastPage * props.perPage < totalRows) lastPage += 1;
pageInfo.value = pages(1, lastPage, 2);
},
);
function previous() {
if (currentPage > 1) changePage(currentPage - 1);
}
function next() {
if (currentPage < lastPage) changePage(currentPage + 1);
}
</script>