通过创建状态变量tabContentArr记录该页签是否已被显示过,来判断TabContent页签的数据是否需要再次请求。
@Entry @ComponentV2 struct TabContentLoading { // 记录页签是否显示过,true已显示,false未显示,默认显示第一个页签 @Local tabContentArr: boolean[] = [true, false, false, false]; tabContents: string[] = ['首页', '推荐', '发现', '我的']; build() { Row() { Column() { Tabs({ barPosition: BarPosition.Start }) { ForEach(this.tabContents, (item: string, index) => { TabContent() { if (this.tabContentArr[index]) { TabChild({ textName: index }) } else { LoadingProgress().width(50) } }.tabBar(item) }, (item: string) => `${item}`) } .onSelected((index) => { if (this.tabContentArr[index]) { return; } // 模拟请求 setTimeout(() => { this.tabContentArr[index] = true; // 显示过设置为true }, 500); }) } .width('100%') } .height('100%') } } @ComponentV2 struct TabChild { @Require @Param textName: number; build() { Column() { Text(this.textName + '') } .width('100%') .height('100%') .alignItems(HorizontalAlign.Center) .justifyContent(FlexAlign.Center) } }