vue实现滚动翻页
vue实现滚动翻页的方法
在Vue中实现滚动翻页(无限滚动)可以通过监听滚动事件或使用现成的库完成。以下是几种常见方法:
监听滚动事件实现
通过计算滚动位置触发加载更多数据:
// 在组件中
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const windowHeight = window.innerHeight;
const scrollHeight = document.documentElement.scrollHeight;
if (scrollTop + windowHeight >= scrollHeight - 100) {
this.loadMore();
}
},
loadMore() {
if (this.isLoading || !this.hasMore) return;
this.isLoading = true;
// 调用API获取更多数据
fetchData().then(res => {
this.list = [...this.list, ...res.data];
this.hasMore = res.hasMore;
}).finally(() => this.isLoading = false);
}
}
使用Intersection Observer API

更高效的现代浏览器API,性能优于滚动事件监听:
// 在模板中添加一个哨兵元素
<template>
<div ref="sentinel" style="height: 1px;"></div>
</template>
// 在组件中
mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
observer.observe(this.$refs.sentinel);
}
使用第三方库
vue-infinite-loading是常用解决方案:

npm install vue-infinite-loading
import InfiniteLoading from 'vue-infinite-loading';
// 在组件中
<template>
<infinite-loading @infinite="loadMore"></infinite-loading>
</template>
methods: {
loadMore($state) {
fetchData().then(res => {
this.list.push(...res.data);
res.hasMore ? $state.loaded() : $state.complete();
});
}
}
优化建议
添加防抖避免频繁触发:
data() {
return {
debounceTimer: null
}
},
methods: {
handleScroll() {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
// 滚动逻辑
}, 200);
}
}
在组件销毁时移除事件监听:
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
对于移动端,建议使用CSS优化滚动性能:
.container {
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}






