在vue3中怎么简单的实现一个下拉分页呢,我们可以使用@scroll="handleScroll" 实现一个简单的滚动分页。代码如下,以下是vue3+ts
<div class="scroll-pagination" @scroll="handleScroll" ref="scrollContainer" >
<div v-for="(item,index) in allList :key="index">
{{item.title}}
</div>
<div v-if="!hasMorePages || totalPages<2 || !allList.length" class="no-data">
暂无更多数据
</div>
<div v-if="hasMorePages && totalPages>1 && allList.length" class="no-data">
加载中
</div>
</div>
import { defineComponent, onMounted, ref, onUnmounted } from 'vue';
export default defineComponent({
name:'allList',
setup( props,{emit} ) {
const scrollContainer = ref<HTMLElement | null>(null)
const page = ref(1)
const totalPages = ref(1)
const hasMorePages = ref(true);
const allList = ref<any>([])
// 以下拖动分页
const handleScroll = () => {
if (!scrollContainer.value) return;
const { scrollTop, clientHeight, scrollHeight } = scrollContainer.value;
if ( scrollTop + clientHeight >= scrollHeight - 10 && !loading.value &&
hasMorePages.value ) {
loading.value = true;
loadMorePages();
}
};
const loadMorePages = () => {
// 在这里实现加载更多页面的逻辑
// 例如,通过API请求获取更多数据
// 当数据加载完成后,更新currentPage、hasMorePages和items的值
page.value += 1;
// 模拟异步加载数据
setTimeout(() => {
if (page.value <= totalPages.value) {
// 假设加载成功,更新加载状态和数据列表
loading.value = false;
getList()
} else {
// 没有更多页面可加载
hasMorePages.value = false;
}
}, 10);
}
async function getList() {
const res:any = await getListApi({
data:{
pageNo:page.value,
pageSize:5
}
})
if(res?.code === '200') {
const list = res.data.records
allList.value = [...allList.value,...list]
totalPages.value = Math.ceil(res.data.total/ 5)
}
}
// 在组件卸载前移除滚动事件监听器
onUnmounted(() => {
if (scrollContainer.value) {
scrollContainer.value.removeEventListener('scroll', handleScroll);
}
})
onMounted(()=>{
getList()
if (scrollContainer.value) {
scrollContainer.value.addEventListener('scroll', handleScroll);
}
})
return {
allList,
scrollContainer,
handleScroll,
loadMorePages,
hasMorePages,
loading,
totalPages
}
}
})
.scroll-pagination {
height: 100%;
overflow-y: scroll;
position: relative;
}
.no-data {
/* 暂无更多数据样式 */
text-align: center;
padding: 20px;
color: #999;
}