通过 List 的 cachedCount 方法可以设置列表中 ListItem/ListItemGroup 的预加载数量,其中 ListItemGroup 将作为一个整体进行计算,ListItemGroup 中的所有 ListItem 会一次性全部加载出来。
declare class ListAttribute extends CommonMethod<ListAttribute> {
/**
* 设置预加载数量
*/
cachedCount(value: number): ListAttribute;
}
- value:预加载数量
接下来,我们来写一个设置预加载数量的示例。
cachedCount 需要搭配 LazyForEach 使用。
首先,定义数据源。
class MyDataSource implements IDataSource {
data: string[] = [];
public totalCount(): number {
return this.data.length
}
public getData(index: number): any {
return this.data[index]
}
registerDataChangeListener(listener: DataChangeListener): void {
}
unregisterDataChangeListener(listener: DataChangeListener): void {
}
}
然后,创建数据源,并在 aboutToAppear 生命周期中填充数据。
@Entry
@Component
struct Index {
/**
* 数据源
*/
names: MyDataSource = new MyDataSource()
aboutToAppear() {
// 填充数据
for (let i = 0; i < 30; i++) {
this.names.data.push(`数据${i}`)
}
}
build() {
List() {
LazyForEach(this.names, (item: string, index: number) => {
ListItem() {
Row() {
Text(item)
.fontSize(30)
.onAppear(() => {
console.log(`子组件已创建:${index}`)
})
}
.width('100%')
.height(100)
}
}, (item: string) => item)
}
.width('100%')
.height('100%')
.cachedCount(10)
}
}
最后,渲染数据,并设置 cachedCount 为 10。
@Entry
@Component
struct Index {
/**
* 数据源
*/
names: MyDataSource = new MyDataSource()
aboutToAppear() {
// 填充数据
for (let i = 0; i < 30; i++) {
this.names.data.push(`数据${i}`)
}
}
build() {
List() {
LazyForEach(this.names, (item: string, index: number) => {
ListItem() {
Row() {
Text(item)
.fontSize(30)
.onAppear(() => {
console.log(`子组件已创建:${index}`)
})
}
.width('100%')
.height(100)
}
}, (item: string) => item)
}
.width('100%')
.height('100%')
.cachedCount(10)
}
}
运行结果:

控制台输出:
子组件已创建:0
子组件已创建:1
子组件已创建:2
子组件已创建:3
子组件已创建:4
子组件已创建:5
子组件已创建:6
子组件已创建:7
应用通过增大 List/Grid 控件的 cachedCount 参数,调整 UI 的加载范围。cachedCount 表示屏幕外 List/Grid 预加载 item 的个数。
如果需要请求网络图片,可以在 item 滑动到屏幕显示之前,提前*载下**好内容,从而减少滑动白块。