在微信小程序開發(fā)文檔中提供了在json文件中配置tab切換的方法,那便是tabBar器钟,其底層原理就是幾個頁面的來回切換孤里,而且此tab只能放在網(wǎng)頁底部或者頭部且有個數(shù)限制累舷,局限性非常大。那么當我們有一個需求是實現(xiàn)一個頁面下tab切換功能而并不局限于在app.json中配置壤圃,在微信小程序中又該怎么做呢陵霉?
話不多說,上源碼:
WXML:
<view class="swiper-tab">
<view class="swiper-tab-list {{currentTab==0 ? 'on' : ''}}" data-current="0" bindtap="swichNav">產(chǎn)品</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>產(chǎn)品</view>
</swiper-item>
<swiper-item>
<view>金融</view>
</swiper-item>
<swiper-item>
<view>理財</view>
</swiper-item>
</swiper>
用三元表達式判斷currentTab==Num是否為真伍绳,如果為真踊挠,動態(tài)添加on類名,執(zhí)行標記樣式冲杀,這樣就實現(xiàn)了上面list列表的切換止毕,至于內(nèi)容重定義了data下的currentTab,讓其與之對應顯示,這樣一個簡單的tab切換功能就實現(xiàn)了漠趁,而且不受位置的限制扁凛,更改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