HarmonyOS Tabs非首次选中页面能不能预加载?

主页面是4个tab tabContent构建的页面,首次进入主页面,默认加载index=0的页面,有没有办法不点击ab,让index=2的页面预加载(可执行aboutToAppear和build方法)?

阅读 493
1 个回答

参考示例demo:

class MyDataSource implements IDataSource {
  private list: number[] = []
  constructor(list: number[]) {
    this.list = list
  }

  totalCount(): number {
    return this.list.length
  }

  getData(index: number): number {
    return this.list[index]
  }

  registerDataChangeListener(listener: DataChangeListener): void {
  }

  unregisterDataChangeListener() {
  }
}

@Entry
@Component
struct Index {
  private swiperController: SwiperController = new SwiperController()
  private data: MyDataSource = new MyDataSource([])
  @State currentIndex: number = 1
  @State showSheet: boolean = false
  @State sheetHeight: number = 300;
  @State showDragBar: boolean = true;

  aboutToAppear(): void {
    let list: number[] = []
    for (let i = 1; i <= 1000; i++) {
      list.push(i);
    }
    this.data = new MyDataSource(list)
  }

  @Builder
  pager() {
    Grid() {
      LazyForEach(this.data, (item: number) => {
        GridItem() {
          Text(item.toString())
            .width(30)
            .height(30)
            .border({ width: 1, color: (this.currentIndex + 1) === item ? Color.Red : Color.Gray, radius: 15 })
            .textAlign(TextAlign.Center)
            .onClick(() => {
              this.currentIndex = item - 1
            })
        }
      }, (item: string) => item)
    }.columnsTemplate("1fr 1fr 1fr 1fr").rowsGap(8)
    .width("100%")
    .height("100%")
  }

  build() {
    Column() {
      Swiper(this.swiperController) {
        LazyForEach(this.data, (item: string) => {
          Text(item.toString())
            .width("100%")
            .height("100%")
            .backgroundColor(0xAFEEEE)
            .textAlign(TextAlign.Center)
            .fontSize(30)
        }, (item: string) => item)
      }
      .layoutWeight(1)
      .cachedCount(2)
      .index($$this.currentIndex)
      .indicator(false)
      .loop(true)
      .duration(300)
      .curve(Curve.Linear)

      Row({ space: 12 }) {
        Text(this.currentIndex + 1+"页,总计"+this.data.totalCount())
      }.margin(5)
      .onClick(() => {
        this.showSheet = true
      })
      .bindSheet($$this.showSheet, this.pager(), {
        height: this.sheetHeight,
        dragBar: this.showDragBar,
        onAppear: () => {
          console.log('BindSheet onAppear.')
        },
        onDisappear: () => {
          console.log('BindSheet onDisappear.')
        }
      })
    }.width('100%')
    .margin({ top: 5 })
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进