在微信小程序开发文档中提供了在json文件中配置tab切换的方法,那便是tabBar,其底层原理就是几个页面的来回切换,而且此tab只能放在网页底部或者头部且有个数限制,局限性非常大。那么当我们有一个需求是实现一个页面下tab切换功能而并不局限于在app.json中配置,在微信小程序中又该怎么做呢?
话不多说,上源码:
WXML:
<view class="swiper-tab">
<block wx:for="{{navBar}}">
<view class="swiper-tab-list {{currentTab==index ? 'on' : ''}}" data-current="{{index}}" bindtap="swichNav">
{{item}}
</view>
</block>
</view>
<swiper current="{{currentTab}}" style="height:{{winHeight - 42}}px" class="swiper-box" duration="300" bindchange="bindChange">
<block wx:for="{{navBar}}">
<swiper-item>
<view>{{item}}</view>
</swiper-item>
</block>
</swiper>
用三元表达式判断currentTab==Num是否为真,如果为真,动态添加on类名,执行标记样式,这样就实现了上面list列表的切换,至于内容重定义了data下的currentTab,让其与之对应显示,这样一个简单的tab切换功能就实现了,而且不受位置的限制,更改css样式可随意布局
=================
WXSS:
.swiper-tab {
width: 100%;
text-align: center;
line-height: 40px;
}
.swiper-tab-list {
font-size: 30rpx;
display: inline-block;
width: 33.33%;
color: #777777;
}
.on {
color: blue;
border-bottom: 2px solid blue;
}
.swiper-box {
display: block;
height: 100%;
width: 100%;
overflow: hidden;
}
.swiper-box view {
text-align: center;
}
JS:
Page({
data: {
winWidth: 0,
winHeight: 0,
currentTab: 0,
navBar: ['产品','金融','理财']
},
onLoad: function() {
var that = this;
/**
* 获取当前设备的宽高
*/
wx.getSystemInfo( {
success: function( res ) {
that.setData( {
winWidth: res.windowWidth,
winHeight: res.windowHeight
});
}
});
},
// tab切换逻辑
swichNav: 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 });
},
})
效果图: