@Entry @Component struct SwiperDeletesDataToPreviousElementOne { private swiperController: SwiperController = new SwiperController(); @State data: number[] = []; @State total: number = 2; @State index: number = 0; aboutToAppear(): void { for (let i = 0; i <= this.total; i++) { this.data.push(i); } } build() { Column({ space: 5 }) { Swiper(this.swiperController) { ForEach(this.data, (item: number) => { Text((item + 1) + '') .width('90%') .height(160) .backgroundColor('#f1f3f5') .textAlign(TextAlign.Center) .fontSize(30); }, (item: string) => item); } .index($$this.index) // 绑定索引状态变量 .indicator(Indicator.digit() .top(200) .fontColor(Color.Gray) .selectedFontColor(Color.Gray) .digitFont({ size: 20, weight: FontWeight.Bold }) .selectedDigitFont({ size: 20, weight: FontWeight.Normal })) .displayArrow(true, false) .cachedCount(3) .loop(false); Row({ space: 10 }) { Button('Add').onClick(() => { this.data.push(++this.total); this.index = this.total; // 修改索引,触发UI更新 }); Button('Remove').onClick(() => { this.data.pop(); this.index -= 1; // 修改索引,触发UI更新 }); }; } .width('100%') .margin({ top: 5 }); } }
效果预览:

@Entry @Component struct SwiperDeletesDataToPreviousElementTwo { private swiperController: SwiperController = new SwiperController(); @State data: number[] = []; @State total: number = 2; index: number = 0; aboutToAppear(): void { for (let i = 0; i <= this.total; i++) { this.data.push(i); } } build() { Column({ space: 5 }) { Swiper(this.swiperController) { ForEach(this.data, (item: number) => { Text((item + 1) + '') .width('90%') .height(160) .backgroundColor('#f1f3f5') .textAlign(TextAlign.Center) .fontSize(30); }, (item: string) => item); } .index($$this.index) // 绑定索引状态变量 .indicator(Indicator.digit() .top(200) .fontColor(Color.Gray) .selectedFontColor(Color.Gray) .digitFont({ size: 20, weight: FontWeight.Bold }) .selectedDigitFont({ size: 20, weight: FontWeight.Normal })) .displayArrow(true, false) .cachedCount(3) .loop(false); Row({ space: 10 }) { Button('Add').onClick(() => { this.data.push(this.total++); this.swiperController.showNext(); }); Button('Remove').onClick(() => { this.data.pop(); this.swiperController.showPrevious(); }); }; } .width('100%') .margin({ top: 5 }); } }
效果预览:
