Web前端 • 共约 288 字 • 预计阅读 1 分钟
Vue封装一个分页器组件
一个分页器组件最重要的四个参数(需要外界传入)
- 当前第几页: pageNo
- 每页展示的数据数量: pageSize
- 共有多少数据: total
- 显示的连续页码: continues
通过以上信息可以计算出来的数据
-
共有多少页: total/pageSize 向上取整
-
显示的连续页码的起始与结束
-
如果总页数小于要显示的连续页码
- 起始为 1
- 结束为总页数
-
如果总页数大于连续页码
-
先计算出当前页码左边和右边要显示几个页码: 连续页码/2 向下取整
-
起始页码: 当前显示的页码-上边计算出来的数据
- 如果小于 1, 那么起始页码等于 1, 结束页码等于要显示的连续页码
-
结束页码: 当前显示的页码+上边计算出来的数据
- 如果大于总页码, 那么起始页码等于总页码-连续页码+1, 结束页码等于总页码
-
-
-
分页器组件
<template>
<div class="pagination">
<button
:disabled="pageNo == 1"
@click="emit('changePage', pageNo - 1)"
>
上一页
</button>
<button v-if="startAndEnd.start > 1">1</button>
<button v-if="startAndEnd.start > 2">···</button>
<button
:class="{
active: pageNo == index + 1,
}"
v-for="(page, index) in startAndEnd.end"
v-show="page >= startAndEnd.start"
@click="emit('changePage', index + 1)"
>
{{ page }}
</button>
<button v-if="startAndEnd.end < totalPage - 1">···</button>
<button v-if="startAndEnd.end < totalPage">{{ totalPage }}</button>
<button
:disabled="pageNo == totalPage"
@click="emit('changePage', pageNo + 1)"
>
下一页
</button>
<button style="margin-left: 30px">共 {{ total }} 条</button>
</div>
</template>
<script setup lang="ts">
import { computed, toRefs, type Ref } from "vue";
const props = defineProps<{
pageNo: number;
pageSize: number;
total: number;
continues: number;
}>();
const { pageNo, pageSize, total, continues } = toRefs(props);
const emit = defineEmits(["changePage"]);
const totalPage = computed(() => {
return Math.ceil(total.value / pageSize.value);
});
const test = () => {
console.log(pageNo.value);
};
const startAndEnd = computed(() => {
let start = 0,
end = 0;
console.log(pageNo.value);
// 如果总页数小于要显示的页数
if (totalPage.value < continues.value) {
start = 1;
end = totalPage.value;
} else {
// 正常情况
start = pageNo.value - Math.floor(continues.value / 2);
end = pageNo.value + Math.floor(continues.value / 2);
}
// 异常情况
if (start < 1) {
start = 1;
end = continues.value;
}
if (end > totalPage.value) {
start = totalPage.value - continues.value + 1;
end = totalPage.value;
}
// debugger;
return {
start,
end,
};
});
</script>
<script lang="ts">
export default {
name: "pagination",
};
</script>
使用分页器组件
<pagination
v-if="store.searchList"
:pageNo="searchParams.pageNo"
:pageSize="searchParams.pageSize"
:total="store.searchList.total"
:continues="5"
@changePage="changePage"
></pagination>
//改变页码并且发送请求
const changePage = (pageNo: number) => {
console.log(pageNo);
searchParams.value.pageNo = pageNo;
store.getSearchList(searchParams.value);
};