注意:本博客理论基础: https://blog.51cto.com/lianghecai/5743179
效果
自定义分页插件:PagePlugin.vue
<script setup lang="ts">
// total :用来传递数据总条数
// pageSize :每页展示几条数据
// currentPage :当前默认页码
// change-page :页码改变时触发的事件,参数为当前页码
const props = defineProps({
//数据总条数
total: {
type: Number,
default: 88
},
//页面大小
pageSize: {
type: Number,
default: 16
},
//当前显示的页码
currentPage: {
type: Number,
default: 1
}
});
let currentNum = ref(props.currentPage);
import {computed, ref} from 'vue'
// 页码显示组合
// 计算总页数
const pages = computed(() => Math.ceil(props.total / props.pageSize ));
const list = computed(() => {
const result = []
// 总页数小于等于5页的时候
if (pages.value <= 5) {
for (let i = 1; i <= pages.value; i++) {
result.push(i)
}
} else {
// 总页数大于5页的时候
// 控制两端的省略号的有无,页码的显示个数与选中页码居中
if (currentNum.value <= 2) {
for (let i = 1; i <= 5; i++) {
result.push(i)
}
} else if (currentNum.value >= 3 && currentNum.value <= pages.value - 2) {
for (let i = currentNum.value - 2; i <= currentNum.value + 2; i++) {
result.push(i)
}
} else if (currentNum.value > pages.value - 2) {
for (let i = pages.value - 4; i <= pages.value; i++) {
result.push(i)
}
}
}
return result;
})
const emit = defineEmits(["changePage"])
function changePage(type) {
// 点击上一页按钮
if (type === false) {
if (currentNum.value <= 1)
return
currentNum.value -= 1
} else if (type === true) {
// 点击下一页按钮
if (currentNum.value >= pages.value)
return
currentNum.value += 1
} else {
// 点击页码
currentNum.value = type
}
emit('changePage',currentNum.value);
}
</script>
<template>
<div class="my-pagination">
<a rel="nofollow" href="javascript:;" :class="{ disabled: currentNum === 1 }" @click="changePage(false)">上一页</a>
<span v-if="currentNum > 3">...</span>
<a
href="javascript:;"
v-for="item in list"
:key="item"
:class="{ active: currentNum === item }"
@click="changePage(item)"
>{{ item }}</a>
<span v-if="currentNum < pages - 2">...</span>
<a rel="nofollow" href="javascript:;" :class="{ disabled: currentNum === pages }" @click="changePage(true)">下一页</a>
</div>
</template>
<style scoped lang="less">
.my-pagination {
display: flex;
justify-content: center;
padding: 30px;
> a {
display: inline-block;
padding: 5px 10px;
border: 1px solid #e4e4e4;
border-radius: 4px;
margin-right: 10px;
&:hover {
color: #27BA9B;
}
&.active {
background: #27BA9B;
color: #fff;
border-color: #27BA9B;
}
&.disabled {
cursor: not-allowed;
opacity: 0.4;
&:hover {
color: #333;
}
}
}
> span {
margin-right: 10px;
}
}
</style>
使用插件
<script setup lang="ts">
import PagePlugin from "@/components/PagePlugin.vue";
function changePage(currentPage){
// alert(currentPage)
console.log(currentPage)
}
</script>
<template>
<!--分页-->
<PagePlugin
:total="total"
:pagesize="pageSize"
:currentPage="pageNum"
@change-page="changePage"/>
</template>