vue实现滚动分页
实现滚动分页的基本思路
滚动分页(Infinite Scroll)是一种常见的前端分页加载方式,当用户滚动到页面底部时自动加载下一页数据。Vue 结合现代前端工具可以轻松实现这一功能。
监听滚动事件
通过监听窗口的滚动事件,判断是否滚动到底部。可以使用 window.addEventListener 或 Vue 的自定义指令。
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.loading || !this.hasMore) return;
this.loading = true;
this.fetchData(this.currentPage + 1);
}
}
使用 Intersection Observer API
Intersection Observer 是一种更高效的滚动监听方式,适合现代浏览器。
data() {
return {
observer: null,
loading: false,
hasMore: true
};
},
mounted() {
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.loading && this.hasMore) {
this.loadMore();
}
});
this.observer.observe(document.querySelector('#load-more-trigger'));
},
beforeDestroy() {
this.observer.disconnect();
},
methods: {
loadMore() {
this.loading = true;
this.fetchData(this.currentPage + 1);
}
}
数据加载与分页逻辑
在 Vue 组件中管理分页状态和数据加载。

data() {
return {
items: [],
currentPage: 1,
totalPages: 1,
loading: false
};
},
methods: {
async fetchData(page) {
if (this.loading) return;
this.loading = true;
try {
const response = await api.fetchItems(page);
this.items = [...this.items, ...response.data];
this.currentPage = page;
this.totalPages = response.totalPages;
} catch (error) {
console.error(error);
} finally {
this.loading = false;
}
}
}
使用第三方库
如果需要更高级的功能,可以考虑使用第三方库如 vue-infinite-loading。
安装:

npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in items" :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: {
async loadMore($state) {
try {
const response = await api.fetchItems(this.currentPage + 1);
this.items.push(...response.data);
this.currentPage++;
if (this.currentPage >= response.totalPages) {
$state.complete();
} else {
$state.loaded();
}
} catch (error) {
$state.error();
}
}
}
};
</script>
优化与注意事项
避免频繁触发滚动事件,可以通过防抖(debounce)优化性能。
methods: {
handleScroll: _.debounce(function() {
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();
}
}, 200)
}
确保在组件销毁时移除事件监听或断开观察器,避免内存泄漏。
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
if (this.observer) this.observer.disconnect();
}






