解决小程序动态改变swiper数据位置被记录问题

解决小程序动态改变swiper数据位置被记录问题

记录一下使用小程序swiper组件做滑动轮播时遇到的问题

1. 如图所示:

在切换tab栏时更换swiper的数据位置会被缓存,此时切换到轮播图只有一张的tab栏时,图片不见了,这时轮播图的位置是上次滑动的位置,因为只有一张图片,所以现在显示的是第二张的位置。

未修改

2. 如何解决:

  • 首先添加一个 current 变量来记录当前滑块的位置
1
2
3
4
5
data () {
return {
current: 0
}
}
  • 然后设置给swiper设置 current 属性以及 @change 方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<swiper
class="swiper-box"
:autoplay="false"
:current="current"
@change="swiperChange"
next-margin="220rpx"
style="height: 312rpx">
<swiper-item
v-for="(item, key) in charmList"
:key="key">
<view class="view-list" @click="jumpArticleDetail($event, item.id)">
<image :src="item.image"></image>
<view class="view-content">
<view class="title">{{item.title}}</view>
<view class="sub-title">{{item.subTitle}}</view>
</view>
</view>
</swiper-item>
</swiper>
  • current改变时会触发 change 事件,将current赋给储存的变量
1
2
3
4
5
methods: {
swiperChange (e) {
this.current = e.detail.current
}
}
  • 当切换 tab 时判断 current 是否大于0,如果大于0的话就让把当前滑块设为0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
changeTabs (key) {
this.tabs.map(item => {
item.active = false
})

this.tabs[key].active = true

this.request(this.tabs[key].id).then(res => {
if (res.code === 200) {
const arr = new Array()

res.data.forEach(item => {
arr.push({
title: item['theme'],
subTitle: item['title'],
image: item['img1']
})
})

this.charmList = arr

if (this.current > 0) {
this.current = 0
}
}
})
}

3. 修改后的效果

修改后

作者

Reself's

发布于

2020-05-28

更新于

2021-02-09

许可协议

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×