vue实现更多加载
Vue实现更多加载功能
实现更多加载功能通常涉及监听滚动事件、判断是否到达页面底部以及异步加载数据。以下是几种常见的实现方式:
滚动监听实现
通过监听滚动事件,判断用户是否滚动到页面底部触发加载:
// 在mounted钩子中添加滚动监听
mounted() {
window.addEventListener('scroll', this.handleScroll);
},
// 在beforeDestroy钩子中移除监听
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.hasMore) return;
this.isLoading = true;
// 调用API获取更多数据
fetchMoreData().then(res => {
this.list = [...this.list, ...res.data];
this.hasMore = res.hasMore;
}).finally(() => {
this.isLoading = false;
});
}
}
使用Intersection Observer API
更现代的实现方式,性能优于滚动监听:
data() {
return {
observer: null,
sentinel: null
}
},
mounted() {
this.sentinel = document.querySelector('#load-more-sentinel');
this.observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.loadMore();
}
});
this.observer.observe(this.sentinel);
},
beforeDestroy() {
this.observer.disconnect();
}
结合分页参数
通常需要配合后端分页参数实现:
loadMore() {
if (this.isLoading || !this.hasMore) return;
this.isLoading = true;
this.page++;
api.getList({
page: this.page,
size: this.pageSize
}).then(res => {
this.list = [...this.list, ...res.data];
this.hasMore = res.data.length >= this.pageSize;
}).finally(() => {
this.isLoading = false;
});
}
组件化实现
可以封装成可复用的加载更多组件:
<template>
<div>
<slot></slot>
<div v-if="loading" class="loading">加载中...</div>
<div v-if="!loading && !noMore" class="no-more">没有更多了</div>
</div>
</template>
<script>
export default {
props: {
loading: Boolean,
noMore: Boolean
}
}
</script>
使用第三方库
如vue-infinite-loading:
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: {
InfiniteLoading
},
methods: {
loadMore($state) {
fetchMoreData().then(res => {
this.list.push(...res.data);
if (res.hasMore) {
$state.loaded();
} else {
$state.complete();
}
}).catch(() => {
$state.error();
});
}
}
}
关键点包括:
- 合理设置加载阈值避免频繁触发
- 添加加载状态避免重复请求
- 处理无更多数据的情况
- 组件销毁时移除事件监听
- 考虑移动端兼容性
实际实现应根据具体项目需求选择合适的方式,并注意性能优化和用户体验。







