vue 实现加载更多
Vue 实现加载更多功能
数据准备与状态管理
在Vue组件中定义必要的数据状态,包括当前页码、每页数据量、总数据量以及数据列表。使用data或ref(Composition API)进行初始化:
data() {
return {
page: 1,
pageSize: 10,
total: 0,
list: [],
loading: false,
noMore: false
}
}
获取数据的方法
创建异步方法用于从API获取数据。该方法需要处理分页参数和加载状态:
methods: {
async fetchData() {
if (this.loading || this.noMore) return;
this.loading = true;
try {
const res = await api.getList({
page: this.page,
pageSize: this.pageSize
});
this.list = [...this.list, ...res.data.list];
this.total = res.data.total;
this.noMore = this.list.length >= this.total;
this.page++;
} finally {
this.loading = false;
}
}
}
滚动监听实现
在mounted钩子中添加滚动事件监听,计算是否到达页面底部:
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollHeight = document.documentElement.scrollHeight;
const scrollTop = document.documentElement.scrollTop;
const clientHeight = document.documentElement.clientHeight;
if (scrollTop + clientHeight >= scrollHeight - 100 && !this.loading) {
this.fetchData();
}
}
}
模板渲染
在模板中渲染列表数据和加载状态:
<template>
<div>
<div v-for="item in list" :key="item.id">
<!-- 列表项内容 -->
</div>
<div v-if="loading">加载中...</div>
<div v-if="noMore">没有更多数据了</div>
</div>
</template>
使用第三方库(可选)
可以考虑使用现成的无限滚动组件,如vue-infinite-loading:
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
methods: {
async onInfinite($state) {
try {
const res = await api.getList({
page: this.page,
pageSize: this.pageSize
});
if (res.data.list.length) {
this.list.push(...res.data.list);
this.page++;
$state.loaded();
} else {
$state.complete();
}
} catch (err) {
$state.error();
}
}
}
}
模板中使用方式:
<infinite-loading @infinite="onInfinite"></infinite-loading>
性能优化建议
- 添加防抖处理滚动事件,避免频繁触发
- 在组件销毁时移除事件监听
- 对API请求进行错误处理
- 使用骨架屏提升用户体验
- 移动端考虑使用Intersection Observer API替代滚动监听







