本文实例为大家分享了vue3封装自己分页组件的具体代码,供大家参考,具体内容如下 背景 在浏览列表类型的数据的时候,如果数据比较多一次性全部请求会出现性能损耗以及加载延迟等问题,那
本文实例为大家分享了vue3封装自己分页组件的具体代码,供大家参考,具体内容如下
在浏览列表类型的数据的时候,如果数据比较多一次性全部请求会出现性能损耗以及加载延迟等问题,那么此时分页组件就起到了关键作用,它可以只请求一部分数据,也不会占用太多的页面空间,想看别的数据可以通过页码的改变来发起请求,刷新页面数据
现在我们自己来封装分页组件
<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 = []
// 总页数小于等于5页的时候
if (pages <= 5) {
for (let i = 1; i <= pages; i++) {
result.push(i)
}
} else {
// 总页数大于5页的时候
// 控制两个极端那边的省略号的有无,页码的显示个数与选中页码居中
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>
使用组件
<XtxPagination
:total="total"
:pagesize="reqParams.pagesize"
:currentPage="1"
@change-page="changePage" />
效果
--结束END--
本文标题: vue3封装自己的分页组件
本文链接: https://www.lsjlt.com/news/136968.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0