在微信小程序开发文档中提供了在json文件中配置tab切换的方法,那便是tabBar,其底层原理就是几个页面的来回切换,而且此tab只能放在网页底部或者头部且有个数限制,局限性非常大。那么当我们有一个需求是实现一个页面下tab切换功能而并不局限于在app.json中配置,在微信小程序中又该怎么做呢?
话不多说,上源码:
WXML:
<view class="swiper-tab">
<view class="swiper-tab-list {{currentTab==0 ? 'on' : ''}}" data-current="0" bindtap="swichNav">产品</view>
<view class="swiper-tab-list {{currentTab==1 ? 'on' : ''}}" data-current="1" bindtap="swichNav">金融</view>
<view class="swiper-tab-list {{currentTab==2 ? 'on' : ''}}" data-current="2" bindtap="swichNav">理财</view>
</view>
<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>
用三元表达式判断currentTab==Num是否为真,如果为真,动态添加on类名,执行标记样式,这样就实现了上面list列表的切换,至于内容重定义了data下的currentTab,让其与之对应显示,这样一个简单的tab切换功能就实现了,而且不受位置的限制,更改css样式可随意布局
=================
WXSS:
.swiper-tab{
width: 100%;
text-align: center;
line-height: 80rpx;}
.swiper-tab-list{ font-size: 30rpx;
display: inline-block;
width: 33.33%;
color: #777777;
}
.on{ color: blue;
border-bottom: 3rpx 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,
},
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 });
},
})
效果图:
list.gif
网友评论