vue3 – 封装自己的分页组件
背景
在浏览列表类型的数据的时候,如果数据比较多一次性全部请求会出现性能损耗以及加载延迟等问题,那么此时分页组件就起到了关键作用,它可以只请求一部分数据,也不会占用太多的页面空间,想看别的数据可以通过页码的改变来发起请求,刷新页面数据
现在我们自己来封装分页组件
组件所需参数
total 属性 :用来传递数据总条数
pagesize 属性 :每页展示几条数据
currentPage 属性 :当前默认页码
change-page 事件 :页码改变时触发的事件,参数为当前页码
组件落地代码my-pagination.vue
<template>
<div class="my-pagination">
<a href="javascript:;" :class="{ disabled: currentPage === 1 }" @click="changePage(false)">上一页</a>
<span v-if="currentPage > 3">...</span>
<a
href="javascript:;"
v-for="item in list"
:key="item"
:class="{ active: currentPage === item }"
@click="changePage(item)"
>{{ item }}</a
>
<span v-if="currentPage < pages - 2">...</span>
<a href="javascript:;" :class="{ disabled: currentPage === pages }" @click="changePage(true)">下一页</a>
</div>
</template>
<script>
import { computed, ref } from 'vue-demi'
export default {
name: 'MyPagination',
props: {
total: {
type: Number,
default: 80
},
pagesize: {
type: Number,
default: 10
}
},
setup(props, { emit, attrs }) {
const currentPage = ref(attrs.currentPage)
const pages = computed(() => Math.ceil(props.total / props.pagesize))
const list = computed(() => {
const result = []
if (pages <= 5) {
for (let i = 1; i <= pages; i++) {
result.push(i)
}
} else {
if (currentPage.value <= 2) {
for (let i = 1; i <= 5; i++) {
result.push(i)
}
} else if (currentPage.value >= 3 && currentPage.value <= pages.value - 2) {
for (let i = currentPage.value - 2; i <= currentPage.value + 2; i++) {
result.push(i)
}
} else if (currentPage.value > pages.value - 2) {
for (let i = pages.value - 4; i <= pages.value; i++) {
result.push(i)
}
}
}
return result
})
const changePage = type => {
if (type === false) {
if (currentPage.value <= 1) return
currentPage.value -= 1
} else if (type === true) {
if (currentPage.value >= pages.value) return
currentPage.value += 1
} else {
currentPage.value = type
}
emit('change-page', currentPage.value)
}
return { currentPage, pages, list, changePage }
}
}
</script>
<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: @xtxColor;
}
&.active {
background: @xtxColor;
color: #fff;
border-color: @xtxColor;
}
&.disabled {
cursor: not-allowed;
opacity: 0.4;
&:hover {
color: #333;
}
}
}
> span {
margin-right: 10px;
}
}
</style>
效果
|