vue实现下拉加载
Vue 实现下拉加载的方法
使用 IntersectionObserver API
IntersectionObserver API 可以监听元素是否进入视口,适合实现下拉加载功能。
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div ref="loader" class="loader">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
isLoading: false
}
},
mounted() {
this.initObserver();
this.loadItems();
},
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.isLoading) {
this.loadMore();
}
});
observer.observe(this.$refs.loader);
},
async loadItems() {
this.isLoading = true;
const newItems = await fetchItems(this.page);
this.items = [...this.items, ...newItems];
this.isLoading = false;
},
loadMore() {
this.page++;
this.loadItems();
}
}
}
</script>
使用滚动事件监听
通过监听滚动事件判断是否到达底部,触发加载更多数据。
<template>
<div @scroll="handleScroll" class="scroll-container">
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<div v-if="isLoading" class="loader">Loading...</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [],
page: 1,
isLoading: false
}
},
mounted() {
this.loadItems();
window.addEventListener('scroll', this.handleScroll);
},
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
},
methods: {
handleScroll() {
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
const clientHeight = document.documentElement.clientHeight || window.innerHeight;
if (scrollTop + clientHeight >= scrollHeight - 100 && !this.isLoading) {
this.loadMore();
}
},
async loadItems() {
this.isLoading = true;
const newItems = await fetchItems(this.page);
this.items = [...this.items, ...newItems];
this.isLoading = false;
},
loadMore() {
this.page++;
this.loadItems();
}
}
}
</script>
使用第三方库
可以使用现成的 Vue 插件如 vue-infinite-loading 简化实现。
安装插件:
npm install vue-infinite-loading
使用示例:
<template>
<div>
<div v-for="item in items" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadMore"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: { InfiniteLoading },
data() {
return {
items: [],
page: 1
}
},
methods: {
async loadMore($state) {
try {
const newItems = await fetchItems(this.page);
if (newItems.length) {
this.items = [...this.items, ...newItems];
this.page++;
$state.loaded();
} else {
$state.complete();
}
} catch (error) {
$state.error();
}
}
}
}
</script>
注意事项
- 确保在组件销毁时移除事件监听,避免内存泄漏。
- 添加防抖或节流处理滚动事件,避免频繁触发。
- 显示加载状态和错误处理,提升用户体验。
- 在移动端需要考虑触摸事件的兼容性。







