1、效果 不做跳转指定页
2、代码
<template>
<div class="page-wrap">
<div>共{{ total }}条,{{ tableData.pageSum }}页</div>
<div class="page">
<!-- v-if="tableData.page > 1" -->
<div
class="page-box arrow"
@click="clickChange('reduce')"
:class="{ disabled: tableData.page == 1 }"
>
<el-icon><ArrowLeft /></el-icon>
</div>
<div
class="page-box"
:class="{
active: tableData.page == item,
}"
v-for="item in pageIndex"
:key="item"
@click="changePage(item)"
>
{{ item }}
</div>
<div
class="page-box arrow"
@click="clickChange('add')"
:class="{ disabled: tableData.page == tableData.pageSum }"
>
<el-icon><ArrowRight /></el-icon>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed, defineEmits } from 'vue';
const $emit = defineEmits(['current-change']);
const props = defineProps({
total: {
type: Number,
default: 0,
},
page: {
type: Number,
default: 1,
},
pageSize: {
type: Number,
default: 20,
},
// visualPage: {
// type: Number,
// default: 10,
// },
});
const tableData = reactive({
page: 1,
pageSum: 0, // 页码数据量 total 120 算
});
watch(
() => props.total,
value => {
tableData.pageSum = Math.ceil(props.total / props.pageSize);
if (props.total == 0) {
tableData.pageSum = 1;
}
},
{
immediate: true,
}
);
const pageIndex = computed(() => {
if (!props.total) {
return [1];
}
let visualPage = 10; // 10: 5[左] 1[当前] 4[右]
// 变量 left 和 right,分别表示当前页码左侧和右侧的最大页码。
let left = 1;
let right = tableData.pageSum;
let arr = []; //显示的页码
// 大于
if (tableData.pageSum >= visualPage) {
// 第6页和倒数第四之间
if (tableData.page > 5 + 1 && tableData.page < tableData.pageSum - 4) {
left = tableData.page - 5;
right = tableData.page + 4;
} else {
// 小于6
if (tableData.page <= 5 + 1) {
left = 1;
right = visualPage;
} else {
// 大于等于倒数第二页
// 倒数10个数
left = tableData.pageSum - (10 - 1);
right = tableData.pageSum;
}
}
}
while (left <= right) {
arr.push(left);
left++;
}
return arr;
});
const handleCurrentChange = () => {
$emit('current-change', tableData.page, props.pageSize);
};
const changePage = item => {
if (tableData.page == item) return;
tableData.page = item;
handleCurrentChange();
};
const clickChange = item => {
if (item == 'reduce') {
if (tableData.page == 1) return;
tableData.page--;
handleCurrentChange();
} else {
if (tableData.page == tableData.pageSum) return;
tableData.page++;
handleCurrentChange();
}
};
</script>
<style scoped lang="scss">
.page-wrap {
// border: 1px solid red;
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
padding-bottom: 0;
}
.page {
display: flex;
text-align: center;
.page-box {
width: 32px;
cursor: pointer;
&:hover {
color: rgba(21, 114, 254, 1);
}
}
.active {
border-radius: 2px;
color: rgba(21, 114, 254, 1);
cursor: default;
}
.disabled {
cursor: not-allowed;
}
.arrow {
position: relative;
top: 2px;
}
}
</style>