美文网首页纵横研究院小程序技术专题社区
微信小程序利用swiper+scroll-view实现Tab切换

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

作者: pudding的旋律 | 来源:发表于2019-12-06 09:59 被阅读0次

微信小程序利用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的时候重新赋值。

相关文章

网友评论

    本文标题:微信小程序利用swiper+scroll-view实现Tab切换

    本文链接:https://www.haomeiwen.com/subject/hqpsgctx.html