<template>
<div class="pagination">
<!-- 只有一页时不显示分页组件 -->
<div v-if="totalPage > 1">
<!-- 首页按钮 -->
<button @click="currentPage = 1">首页</button>
<!-- 上一页按钮 -->
<button @click="prevPage" :disabled="currentPage === 1">上一页</button>
<!-- 页码显示 -->
<button
v-for="page in pages"
:key="page"
@click="currentPage = page"
:class="{active: currentPage === page}"
>
{{ page }}
</button>
<!-- 下一页按钮 -->
<button @click="nextPage" :disabled="currentPage === totalPage">下一页</button>
<!-- 尾页按钮 -->
<button @click="currentPage = totalPage">尾页</button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
export default defineComponent({
props: {
// 总数据条数
total: {
type: Number,
required: true
},
// 每页显示条数
pageSize: {
type: Number,
default: 10
}
},
setup(props, { emit }) {
const totalPage = ref(Math.ceil(props.total / props.pageSize)); // 总页数
const currentPage = ref(1); // 当前页码
const pages = ref<number[]>([]); // 要显示的页码数组
// 计算页码数组
const calculatePages = () => {
pages.value = [];
const totalPageNum = totalPage.value;
const middle = 5;
for (let i = 0; i < totalPageNum; i++) {
if (i < middle - 1 || i > totalPageNum - middle) {
// 当前页码靠近首页或尾页时,显示更多的页码
pages.value.push(i + 1);
} else if (currentPage.value < totalPageNum - middle && currentPage.value > middle) {
// 当前页码处于中间时,显示当前页码前后的页码
if (i === middle - 2 || i === middle - 1 || i === middle || i === middle + 1 || i === middle + 2) {
pages.value.push(i + 1);
}
} else {
pages.value.push(i + 1);
}
}
};
// 监听当前页码变化
watch(currentPage, (newVal) => {
emit('update:currentPage', newVal);
calculatePages();
});
// 监听总数据条数和每页显示条数变化
watch([() => props.total, () => props.pageSize], ()
评论已关闭