微信小程序tab切换功能的实现

3,953 阅读1分钟
1、取到后台数据wxml页面for循环:

 //tab标题
<view class="swiper-tab" style="width:{{windowWidth}}">  
      <view wx:for="{{tabList}}" class=" {{currentTab==index?'active':'swiper-tab-item'}}" 
        data-current="{{index}}" bindtap="clickTab" wx:key="id">{{item.name}}</view>
</view>


//tab对应内容
swiper current="{{currentTab}}" class="swiper-box" duration="300" style="height:{{winHeight - 31}}px" bindchange="bindChange">
    <swiper-item>
        <view>产品</view>
    </swiper-item>
    <swiper-item>
        <view>金融</view>
    </swiper-item>
    <swiper-item>
        <view>理财</view>
    </swiper-item>
</swiper>

2、wxss页面:

.swiper-tab-item {  
color: #434343;  
display: inline-block; 
 width: 200rpx; 
 text-align: center; 
 font-size: 27rpx;
}
.swiper-tab {  
text-align: left; 
 line-height: 80rpx; 
 white-space: nowrap; 
 overflow: auto;
}
.active { 
 display: inline-block; 
 color: #f65959; 
border-bottom: 4rpx solid #f65959; 
 width: 200rpx; 
 text-align: center; 
 font-size: 27rpx;
}

3,js页面:

Page({
    data: {
        winWidth: 0,
        winHeight: 0,
        currentTab: 0,
    },
    onLoad: function() {

        var that = this;

        /**
         * 获取当前设备的宽高
         */
        wx.getSystemInfo( {

            success: function( res ) {
                that.setData( {
                    winWidth: res.windowWidth,
                    winHeight: res.windowHeight
                });
            }

        });
    },
      
 //  tab切换逻辑
    clickTab: function( e ) {
        var that = this;

        if( this.data.currentTab === e.target.dataset.current ) {
            return false;
        } else {
            that.setData( {
                currentTab: e.target.dataset.current
            })
        }
    },

    bindChange: function( e ) {

        var that = this;
        that.setData( { currentTab: e.detail.current });

    },
})