Vue封装一个分页器组件

一个分页器组件最重要的四个参数(需要外界传入)

  • 当前第几页: pageNo
  • 每页展示的数据数量: pageSize
  • 共有多少数据: total
  • 显示的连续页码: continues

通过以上信息可以计算出来的数据

  • 共有多少页: total/pageSize 向上取整

  • 显示的连续页码的起始与结束

    • 如果总页数小于要显示的连续页码

      • 起始为 1
      • 结束为总页数
    • 如果总页数大于连续页码

      • 先计算出当前页码左边和右边要显示几个页码: 连续页码/2 向下取整

        • 起始页码: 当前显示的页码-上边计算出来的数据

          • 如果小于 1, 那么起始页码等于 1, 结束页码等于要显示的连续页码
        • 结束页码: 当前显示的页码+上边计算出来的数据

          • 如果大于总页码, 那么起始页码等于总页码-连续页码+1, 结束页码等于总页码

分页器组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<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>

使用分页器组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
                  <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);
};
作者

cuicui

发布于

2022-12-04

更新于

2023-04-23

许可协议

评论