Swiper渲染组件数据时自动返回上一幻灯片问题排查
问题:Swiper切换到Slide2后自动返回Slide1
我有两个Swiper幻灯片(Slide1和Slide2),Slide1内设有生成数据的按钮,生成的数据需展示在Slide2中。但点击按钮生成数据并在Slide2渲染后,页面会立即返回Slide1。
.ts 文件代码
dispatchPayment(info: any, dn: any): Promise<any> { return new Promise((resolve, reject) => { this.store.dispatch(new GenerateAcion({ info, dn })); this.store.select(PaymentState.paymentStatus).subscribe(state => { if (state.paymentSuccess) { const result = {} resolve(result); } else if (state.paymentError) { reject(state.paymentError); } }); }); } async generarCupon() { const payload = ... const dn = ... try { const result = await this.dispatchPayment(payload, dn); this.cdr.detectChanges(); if(result){ console.log("result", result); this.swiper.slideTo(3, 1000); } } catch (error) { console.error('failed:', error); } }
.html 文件代码
<div class="modal-outer"> <swiper-container (afterinit)="swiperReady()" #slider allow-touch-move="false" [stopOnLastSlide]="true" [loop]="false" > <swiper-slide style="min-height: 500px;"> <div class="modal-wrap"> <ion-button fill="solid" shape="round" color="success" (click)="generarCupon()"> Generate </ion-button> </div> </swiper-slide> <swiper-slide> <div class="modal-wrap"> <div class="refrece-input"> <ion-label>Reference</ion-label> <ion-input type="number" value="{{finalResult?.referencia}}" readonly style="font-size: 18px"></ion-input> </div> <div class="price-detail"> <span>Monto</span> <h2>$ {{finalResult?.costo}} <span>MXN</span></h2> </div> </div> </swiper-slide> </swiper-container> </div>
当前行为
点击Slide1的按钮后,页面跳转至Slide2随即返回Slide1。
预期行为
点击按钮后,正常展示获取到的数据并停留在Slide2。
解决方法
1. 清理未终止的Store订阅
dispatchPayment中对store.select的订阅未手动终止,当状态再次变化时会重复触发逻辑,导致意外跳转。修改代码添加订阅终止:
dispatchPayment(info: any, dn: any): Promise<any> { return new Promise((resolve, reject) => { const subscription = this.store.select(PaymentState.paymentStatus).subscribe(state => { if (state.paymentSuccess) { const result = {}; resolve(result); subscription.unsubscribe(); // 成功后终止订阅 } else if (state.paymentError) { reject(state.paymentError); subscription.unsubscribe(); // 失败后终止订阅 } }); }); }
2. 修正Slide索引错误
Swiper的slideTo方法索引从0开始,你只有2个幻灯片(索引0和1),原代码中slideTo(3, 1000)是无效索引,会触发Swiper异常行为。改为:
async generarCupon() { const payload = ... const dn = ... try { const result = await this.dispatchPayment(payload, dn); this.finalResult = result; // 确保数据赋值给渲染变量 if(result){ console.log("result", result); this.swiper.slideTo(1, 1000); // 切换到第二个幻灯片(索引1) } } catch (error) { console.error('failed:', error); } }
3. 移除不必要的手动变更检测
cdr.detectChanges()可能触发组件重渲染,导致Swiper状态被重置。如果数据绑定逻辑正常,直接移除该调用即可。
4. 确保Swiper实例正确获取
通过ViewChild更可靠地获取Swiper实例:
@ViewChild('slider') slider!: ElementRef; swiperReady() { this.swiper = this.slider.nativeElement.swiper; }
内容的提问来源于stack exchange,提问作者LAUTARO
相关产品推荐
相关产品推荐

