vue实现滚动分页加载
Vue 实现滚动分页加载
监听滚动事件
通过监听滚动事件判断是否到达页面底部,触发加载更多数据。在组件的 mounted 钩子中添加滚动监听,在 beforeDestroy 钩子中移除监听以避免内存泄漏。
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight - 100) {
this.loadMore();
}
}
}
数据加载逻辑
定义 loadMore 方法,通过 API 请求获取分页数据。使用 loading 和 finished 状态避免重复请求或无效请求。
data() {
return {
list: [],
page: 1,
pageSize: 10,
loading: false,
finished: false
};
},
methods: {
async loadMore() {
if (this.loading || this.finished) return;
this.loading = true;
try {
const res = await fetchData(this.page, this.pageSize);
if (res.data.length === 0) {
this.finished = true;
} else {
this.list = [...this.list, ...res.data];
this.page++;
}
} catch (error) {
console.error(error);
} finally {
this.loading = false;
}
}
}
使用第三方库优化
如果需要更简单的实现,可以使用 vue-infinite-scroll 或 vant 等第三方库。以 vant 为例:
<template>
<van-list
v-model="loading"
:finished="finished"
@load="loadMore"
>
<div v-for="item in list" :key="item.id">{{ item.name }}</div>
</van-list>
</template>
性能优化
对于大量数据渲染,使用虚拟滚动技术(如 vue-virtual-scroller)减少 DOM 节点数量,提升性能。
<template>
<RecycleScroller
:items="list"
:item-size="50"
key-field="id"
>
<template v-slot="{ item }">
<div>{{ item.name }}</div>
</template>
</RecycleScroller>
</template>
注意事项
- 滚动监听需考虑节流(如使用
lodash.throttle)避免频繁触发。 - 移动端可能需要额外处理
touch事件。 - 分页接口需支持页码和每页条数参数。






