vue滚动实现换页
Vue 滚动换页实现方法
监听滚动事件
在Vue组件中,通过@scroll或window.addEventListener监听滚动事件。判断滚动位置是否达到阈值,触发换页逻辑。
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollY = window.scrollY;
const windowHeight = window.innerHeight;
const documentHeight = document.body.scrollHeight;
if (scrollY + windowHeight >= documentHeight - 100) {
this.loadNextPage();
}
}
}
使用第三方库
安装vue-infinite-scroll等专门处理无限滚动的库,简化实现过程。
npm install vue-infinite-scroll
<template>
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy">
<!-- 内容列表 -->
</div>
</template>
<script>
import infiniteScroll from 'vue-infinite-scroll';
export default {
directives: { infiniteScroll },
methods: {
loadMore() {
this.busy = true;
// 加载数据逻辑
this.busy = false;
}
}
}
</script>
滚动容器内分页
对于固定高度的容器,监听容器滚动而非全局滚动。
<template>
<div class="scroll-container" @scroll="handleContainerScroll">
<!-- 内容列表 -->
</div>
</template>
<style>
.scroll-container {
height: 500px;
overflow-y: auto;
}
</style>
<script>
methods: {
handleContainerScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
if (scrollTop + clientHeight >= scrollHeight - 50) {
this.loadNextPage();
}
}
}
</script>
节流优化
避免滚动事件频繁触发,使用lodash的throttle或自定义节流函数。

import { throttle } from 'lodash';
methods: {
handleScroll: throttle(function() {
// 滚动处理逻辑
}, 300)
}
注意事项
- 确保在组件销毁时移除事件监听
- 加载新数据时显示加载状态
- 所有数据加载完成后禁用滚动监听
- 移动端需要考虑触摸滚动兼容性






