vue实现滚动翻页
实现滚动翻页的基本思路
滚动翻页通常通过监听滚动事件,判断用户是否滚动到页面底部,触发数据加载。Vue中可通过结合v-infinite-scroll指令或手动监听滚动事件实现。
使用v-infinite-scroll指令(Element UI)
若项目使用Element UI,可直接使用其内置的无限滚动指令:
<template>
<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="50">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
busy: false,
page: 1
};
},
methods: {
async loadMore() {
this.busy = true;
const newData = await fetchData(this.page++);
this.list.push(...newData);
this.busy = false;
}
}
};
</script>
手动实现滚动监听
无UI库依赖时,可通过原生滚动事件实现:
<template>
<div class="scroll-container" @scroll="handleScroll">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div v-if="loading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
loading: false,
page: 1,
hasMore: true
};
},
methods: {
async handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
const isBottom = scrollTop + clientHeight >= scrollHeight - 50;
if (isBottom && !this.loading && this.hasMore) {
this.loading = true;
const newData = await fetchData(this.page++);
this.list.push(...newData);
this.hasMore = newData.length > 0;
this.loading = false;
}
}
},
mounted() {
this.handleScroll({ target: document.querySelector('.scroll-container') });
}
};
</script>
<style>
.scroll-container {
height: 500px;
overflow-y: auto;
}
</style>
关键注意事项
节流处理
滚动事件高频触发,需添加节流逻辑避免重复请求:
import { throttle } from 'lodash';
methods: {
handleScroll: throttle(function(e) {
// 原有逻辑
}, 500)
}
数据加载状态
必须通过loading或busy变量控制请求并发,防止重复加载。
空数据判断
当接口返回空数组时,应设置hasMore为false停止继续请求。
容器高度限制
滚动容器需设置固定高度(如height: 500px)并启用overflow-y: auto。

性能优化建议
- 使用虚拟滚动(如
vue-virtual-scroller)处理超长列表 - 分页大小不宜过大,建议每次加载10-20条数据
- 销毁页面时移除滚动监听:
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}






