vue实现上拉加载
Vue 实现上拉加载
使用 Intersection Observer API
Intersection Observer API 可以监听元素是否进入视口,适合实现上拉加载。
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div ref="loader" v-if="!isLoading && hasMore">加载更多...</div>
<div v-if="isLoading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
isLoading: false,
hasMore: true,
page: 1
};
},
mounted() {
this.initObserver();
this.loadData();
},
methods: {
initObserver() {
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !this.isLoading && this.hasMore) {
this.loadData();
}
});
observer.observe(this.$refs.loader);
},
async loadData() {
this.isLoading = true;
try {
const newData = await fetchData(this.page);
this.list = [...this.list, ...newData];
this.page++;
this.hasMore = newData.length > 0;
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
}
}
};
</script>
使用滚动事件监听
通过监听滚动事件,计算滚动位置触发加载。
<template>
<div ref="container" @scroll="handleScroll">
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<div v-if="isLoading">加载中...</div>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
isLoading: false,
hasMore: true,
page: 1
};
},
mounted() {
this.loadData();
},
methods: {
handleScroll() {
const container = this.$refs.container;
const scrollBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
if (scrollBottom < 50 && !this.isLoading && this.hasMore) {
this.loadData();
}
},
async loadData() {
this.isLoading = true;
try {
const newData = await fetchData(this.page);
this.list = [...this.list, ...newData];
this.page++;
this.hasMore = newData.length > 0;
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
}
}
};
</script>
使用第三方库
Vue-infinite-loading 是一个专门用于无限滚动的 Vue 插件。
安装:
npm install vue-infinite-loading
使用:
<template>
<div>
<div v-for="item in list" :key="item.id">{{ item.content }}</div>
<infinite-loading @infinite="loadData"></infinite-loading>
</div>
</template>
<script>
import InfiniteLoading from 'vue-infinite-loading';
export default {
components: {
InfiniteLoading
},
data() {
return {
list: [],
page: 1
};
},
methods: {
async loadData($state) {
try {
const newData = await fetchData(this.page);
this.list = [...this.list, ...newData];
this.page++;
if (newData.length) {
$state.loaded();
} else {
$state.complete();
}
} catch (error) {
$state.error();
}
}
}
};
</script>
注意事项
- 确保在组件销毁时移除事件监听或断开 Intersection Observer。
- 添加防抖或节流避免频繁触发加载。
- 处理加载失败的情况,提供重试机制。
- 移动端需要考虑滚动性能优化。







