uniapp实现懒加载
uniapp实现懒加载的方法
图片懒加载
在uniapp中,可以使用<image>标签的lazy-load属性实现图片懒加载。该属性仅在page为scroll-view时生效,且需要设置scroll-view的高度。
<scroll-view scroll-y style="height: 100vh;">
<image
v-for="(item, index) in list"
:key="index"
:src="item.src"
lazy-load
mode="aspectFill"
></image>
</scroll-view>
列表数据懒加载
对于长列表数据的懒加载,可以通过监听scroll-view的@scrolltolower事件或页面的onReachBottom生命周期实现。
export default {
data() {
return {
list: [],
page: 1,
loading: false,
noMore: false
}
},
methods: {
loadMore() {
if (this.loading || this.noMore) return;
this.loading = true;
// 模拟异步请求
setTimeout(() => {
const newData = Array(10).fill(0).map((_,i) => ({
id: this.list.length + i,
src: `https://picsum.photos/200/300?random=${this.list.length + i}`
}));
this.list = [...this.list, ...newData];
this.page++;
this.loading = false;
// 假设总共30条数据
if (this.list.length >= 30) {
this.noMore = true;
}
}, 1000);
}
},
onReachBottom() {
this.loadMore();
}
}
组件懒加载
使用vue的异步组件配合uniapp的easycom机制可以实现组件懒加载。

在pages.json中配置:
{
"easycom": {
"^lazy-(.*)": "@/components/lazy/$1.vue"
}
}
创建异步组件:

// components/lazy/my-component.vue
export default {
name: 'lazy-my-component',
// 组件实现
}
使用时直接按需引入:
<template>
<lazy-my-component v-if="showComponent" />
</template>
注意事项
- 图片懒加载需要真机调试,部分模拟器可能无法正常显示效果
- 列表懒加载应配合加载状态提示和没有更多数据提示
- 组件懒加载适用于较大且不立即需要的组件
- iOS平台需要确保
scroll-view有明确的高度值
通过以上方法可以有效减少首屏加载时间,提升用户体验。根据实际需求选择适合的懒加载方案,也可以组合使用多种方式。






