vue实现滚动分页
Vue 实现滚动分页的方法
监听滚动事件实现分页加载
通过监听滚动事件判断是否到达页面底部,触发加载更多数据。在 Vue 组件中添加以下代码:
mounted() {
window.addEventListener('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() {
if (this.isLoading || this.noMoreData) return;
this.isLoading = true;
// 调用API获取更多数据
fetchData().then(res => {
this.list = [...this.list, ...res.data];
this.isLoading = false;
if (res.data.length === 0) {
this.noMoreData = true;
}
});
}
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
使用 Intersection Observer API 实现
Intersection Observer API 提供更高效的方式监测元素是否进入视口:
data() {
return {
observer: null,
loadingElement: null
}
},
mounted() {
this.loadingElement = document.querySelector('#loading');
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
this.observer.observe(this.loadingElement);
},
methods: {
loadMore() {
// 同上面的加载逻辑
}
},
beforeDestroy() {
if (this.observer) {
this.observer.disconnect();
}
}
使用第三方库实现
可以借助现成的 Vue 插件如 vue-infinite-loading 简化实现:

安装插件:
npm install vue-infinite-loading
在组件中使用:

import InfiniteLoading from 'vue-infinite-loading';
export default {
components: {
InfiniteLoading
},
methods: {
loadMore($state) {
fetchData().then(res => {
if (res.data.length) {
this.list.push(...res.data);
$state.loaded();
} else {
$state.complete();
}
}).catch(() => {
$state.error();
});
}
}
}
模板部分:
<infinite-loading @infinite="loadMore">
<div slot="no-more">没有更多数据了</div>
<div slot="no-results">暂无数据</div>
</infinite-loading>
性能优化建议
添加防抖函数避免频繁触发滚动事件:
debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
// 使用方式
mounted() {
window.addEventListener('scroll', this.debounce(this.handleScroll, 200));
}
对于大量数据渲染,建议使用虚拟滚动技术(如 vue-virtual-scroller)提升性能。
注意事项
确保在组件销毁时移除事件监听器,避免内存泄漏。分页请求需要添加锁机制防止重复请求,同时要处理加载状态和没有更多数据的情况。






