vue实现图片无限滚动
实现图片无限滚动的思路
无限滚动的核心逻辑是监听滚动事件,在用户接近底部时加载更多数据。对于图片列表,需要考虑性能优化以避免卡顿。
基础实现步骤
安装依赖(如需要)
npm install vue-infinite-loading
模板部分代码
<template>
<div class="image-container" @scroll="handleScroll">
<div v-for="(image, index) in images" :key="index">
<img :src="image.url" :alt="image.alt">
</div>
<div v-if="loading" class="loading">加载中...</div>
</div>
</template>
脚本部分代码
<script>
export default {
data() {
return {
images: [],
page: 1,
loading: false,
hasMore: true
}
},
methods: {
async fetchImages() {
if (!this.hasMore || this.loading) return;
this.loading = true;
try {
const newImages = await this.$api.getImages(this.page);
if (newImages.length) {
this.images = [...this.images, ...newImages];
this.page++;
} else {
this.hasMore = false;
}
} finally {
this.loading = false;
}
},
handleScroll(e) {
const { scrollTop, clientHeight, scrollHeight } = e.target;
const bottomThreshold = 100;
if (scrollHeight - (scrollTop + clientHeight) < bottomThreshold) {
this.fetchImages();
}
}
},
mounted() {
this.fetchImages();
}
}
</script>
性能优化方案
使用Intersection Observer API替代scroll事件监听

const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
this.fetchImages();
}
}, {
threshold: 0.1
});
observer.observe(this.$refs.loadingTrigger);
添加图片懒加载
<img v-lazy="image.url" :alt="image.alt">
使用虚拟滚动技术
npm install vue-virtual-scroller
使用第三方库
vue-infinite-loading示例

<infinite-loading @infinite="fetchImages">
<div slot="no-more">没有更多了</div>
<div slot="no-results">暂无数据</div>
</infinite-loading>
注意事项
确保API支持分页查询,通常需要page和pageSize参数
const params = {
page: this.page,
pageSize: 20
};
在组件销毁时移除事件监听
beforeDestroy() {
window.removeEventListener('scroll', this.handleScroll);
}
考虑添加防抖处理频繁触发
import { debounce } from 'lodash';
methods: {
handleScroll: debounce(function(e) {
// 滚动逻辑
}, 200)
}






