uni-app H5下 swiper 控制滑动表现异常问题

uni-app H5下 swiper 控制滑动表现异常问题

开发环境 版本号 项目创建方式
Windows windwos10 HBuilderX

示例代码:

<template>  
<view>  
<swiper :indicator-dots="true" :autoplay="false" :interval="3000" :duration="1000" circular  
current="current">
<swiper-item>
<view class="swiper-item">111</view>
</swiper-item>
<swiper-item>
<view class="swiper-item">222</view>
</swiper-item>
<swiper-item>
<view class="swiper-item">333</view>
</swiper-item>
</swiper>  
<view>当前索引:{{current}}</view>  
<button type="default" @click="changeValue(true)">+</button>  
<button type="default" @click="changeValue(false)">-</button>  
</view>
</template>  
<script>
export default {
data() {
return {
current: 0
}
},
methods: {
changeValue(val) {
let oldValue = this.current;
let newValue = 0;  

if (val) {  
newValue = oldValue + 1 > 2 ? 0 : oldValue + 1;  
} else {  
newValue = oldValue - 1 < 0 ? 2 : oldValue - 1;  
}  

this.current = newValue;  
}  
}  
}
</script>

操作步骤:

使用示例代码 H5 运行即可复现

预期结果:

向上滑动一个元素,从第三个元素滑动到第二个元素

实际结果:

当前在第三个元素,瞬间从第一个元素开始然后滑动到第二个元素

bug描述:

三个 swiper-item 元素,滑动到第三个元素时向上个元素,表现异常。 本身是在第三个元素,会突然从第一个元素开始滑动到第二个元素

视频


更多关于uni-app H5下 swiper 控制滑动表现异常问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

示例代码

更多关于uni-app H5下 swiper 控制滑动表现异常问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在H5平台下,swiper组件的current属性绑定确实存在已知的兼容性问题。问题主要出现在通过编程方式修改current值时,swiper内部状态未能正确同步。

从你的代码分析,当current=2(第三个元素)时,执行减一操作,理论上应该滑动到第二个元素。但实际表现是swiper组件先重置到第一个元素,再滑动到目标位置。

建议改用swiper的change事件来维护当前索引状态:

data() {
  return {
    current: 0
  }
},
methods: {
  onSwiperChange(e) {
    this.current = e.detail.current
  },
  changeValue(val) {
    let total = 3 // swiper-item总数
    let newValue = val ? 
      (this.current + 1) % total : 
      (this.current - 1 + total) % total
    this.current = newValue
  }
}

同时在模板中添加change事件监听:

<swiper 
  :current="current"
  [@change](/user/change)="onSwiperChange"
  circular
  :indicator-dots="true">
  <!-- swiper-items -->
</swiper>
回到顶部