300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 微信小程序利用swiper+scroll-view实现Tab切换

微信小程序利用swiper+scroll-view实现Tab切换

时间:2020-04-06 08:04:26

相关推荐

微信小程序利用swiper+scroll-view实现Tab切换

微信小程序利用swiper+scroll-view实现Tab切换

先放一张效果图

需要实现的功能逻辑:

1、当用户点击tab的时候,tab样式发生改变,并且下方对应的展示内容也发生改变。

2、当用户滑动下方内容时,会切换内容,并且上方的tab也会根据对应的展示内容改变选中状态

关键问题:如何将tab和下方的内容对应起来?

思路:

设置一个currentIndex变量,tab的选中状态以及展示的内容都根据这一个变量来进行切换。并且在用户触发点击tab事件和滑动内容事件的时候,都会更新这个currentIndex的值。

tab部分的wxml:

<view class="nav_wrap"><scroll-view class="nav" scroll-x scroll-left="{{navScrollLeft}}"><view bindtap="activeNav" data-index="{{index}}" class="nav_item {{index===currentIndex?'active':''}}" wx:for="{{navList}}" wx:key="{{index}}">{{item.text}}</view></scroll-view></view>

tab部分的js:

activeNav(e) {this.setData({currentIndex: e.currentTarget.dataset.index,navScrollLeft: e.detail.current >= 5 ? ((e.detail.current) * 80) : 0})},

1、这里tab选中状态是根据currentIndex开进行判断的,如果currentIndex等于当前节点绑定的index,就给该节点加上选中时的class。

2、使用data-index="{{index}}"将index值绑定在该节点上,当用户点击tab时会触发activeNav事件。该事件会用e.currentTarget.dataset.index获取该节点绑定的index的值,并将这个值赋给currentIndex。

3、因为我这里的tab数量较多,所以还设置了一个navScrollLeft,用来自动改变scroll-view的离左侧的距离。这样当tab切换到第 6个以及6个之后的时候,可以从视觉角度上让该tab展示在第一个tab的位置。

swiper部分的wxml:

<swiper style="height:{{clientHeight?clientHeight+'px':auto}}" current="{{currentIndex}}" bindchange="changeTab"><swiper-item><view class="slide"><navigator><swiper autoplay indicator-dots circular><swiper-item wx:for="{{swiperList}}" wx:key="{{index}}"><image src="{{item.imgSrc}}" mode='widthFix'></image></swiper-item></swiper></navigator></view><view class="vedioWrap"><navigator url="../detail/detail?id={{item.id}}" class="vedioList" wx:for="{{vedioList}}" wx:key="index"><image src="{{item.imgSrc}}" mode="widthFix"></image><view class="text">{{item.videoTitle}}</view></navigator></view></swiper-item><swiper-item wx:for="{{contentList}}" wx:key="{{index}}">{{item.text}}</swiper-item></swiper>

swiper部分的js:

changeTab(e){this.setData({currentIndex: e.detail.current,navScrollLeft: e.detail.current>=5?((e.detail.current) * 80):0})},

1、swiper里展示的内容通过设置current="{{currentIndex}}"属性来根据currentIndex进行改变。

2、当用户滑动内容时,设置 bindchange="changeTab"来触发changeTab事件。该事件将当前内容的索引值赋给currentIndex。

3、这里的swiper的高度是通过计算获取的。因为这里展示的内容是通过后台接口获取并渲染出来的,所以不能给他一个固定值,又不能不给,因为swiper的默认高度只有150px,所以大家一定要根据自己的情况去将这个值计算出来在切换tab的时候重新赋值。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。