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 = window.innerHeight;
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获取更多数据
fetchMoreData().then(res => {
this.list = [...this.list, ...res.data];
this.isLoading = false;
if (res.data.length === 0) {
this.noMoreData = true;
}
});
}
}
使用 IntersectionObserver API
利用现代浏览器支持的 IntersectionObserver 实现更高效的底部检测,避免频繁触发滚动事件。

mounted() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
observer.observe(this.$refs.loadMoreTrigger);
},
methods: {
loadMore() {
if (this.isLoading || this.noMoreData) return;
this.isLoading = true;
fetchMoreData().then(res => {
this.list = [...this.list, ...res.data];
this.isLoading = false;
if (res.data.length === 0) {
this.noMoreData = true;
}
});
}
}
结合分页参数
在请求数据时携带分页参数,确保每次加载更多数据时获取正确的下一页数据。
data() {
return {
list: [],
page: 1,
pageSize: 10,
isLoading: false,
noMoreData: false
};
},
methods: {
loadMore() {
if (this.isLoading || this.noMoreData) return;
this.isLoading = true;
fetchData(this.page, this.pageSize).then(res => {
this.list = [...this.list, ...res.data];
this.page++;
this.isLoading = false;
if (res.data.length < this.pageSize) {
this.noMoreData = true;
}
});
}
}
使用第三方库
对于复杂场景,可以使用第三方库如 vue-infinite-loading 简化实现。

安装依赖:
npm install vue-infinite-loading
使用示例:
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.name }}</div>
<infinite-loading @infinite="loadMore"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
methods: {
loadMore($state) {
fetchMoreData().then(res => {
this.list = [...this.list, ...res.data];
if (res.data.length) {
$state.loaded();
} else {
$state.complete();
}
});
}
}
};
</script>
注意事项
- 避免重复请求:在加载数据时设置
isLoading标志位,防止重复触发。 - 数据为空处理:当返回数据为空时,标记
noMoreData并显示提示信息。 - 性能优化:对于大量数据,考虑虚拟滚动技术(如
vue-virtual-scroller)提升渲染性能。 - 移动端适配:在移动端可能需要调整触发加载的阈值,确保用户体验流畅。






