目前開發(fā)微信小程序,需求是要在非首頁實(shí)現(xiàn)tabbar的切換效果,但是,官方文檔的tabbar只能在首頁使用,而且還有個坑,tabbar的第一個頁面必須是app.json文件pages數(shù)組的第一個,不然顯示不出來。
接下來說一下如何在非首頁實(shí)現(xiàn)tabbar效果,這個效果在Android里面非常的簡單,使用
fragment進(jìn)行切換就可以實(shí)現(xiàn),那么也是把這種思維帶到了小程序中,使用component進(jìn)行切換,先上代碼。
page.js
Page({
data: {
currentTab: 0,
items: [{
"iconPath": "/icon/overview.png",
"selectedIconPath": "/icon/overview_sel.png",
"text": "首頁"
},
{
"iconPath": "/icon/overview.png",
"selectedIconPath": "/icon/overview_sel.png",
"text": "推薦"
},
{
"iconPath": "/icon/overview.png",
"selectedIconPath": "/icon/overview_sel.png",
"text": "我的"
}
]
},
/**
* 選項(xiàng)卡點(diǎn)擊事件
*/
tabbarClick: function(e) {
let that = this;
if (this.data.currentTab === e.target.dataset.current) {
return false;
} else {
that.setData({
currentTab: e.target.dataset.current
})
}
},
})
page.json
{
"usingComponents": {
"my-component": "/components/component-tag-name",
"aa":"/aa/aa",
"bb":"/bb/bb"
}
}
page.wxml
<view class='root'>
<view class='box-h'>
<view wx:if="{{currentTab == 0}}">
<my-component class='component' />
</view>
<view wx:if="{{currentTab == 1}}">
<aa class='component' />
</view>
<view wx:if="{{currentTab == 2}}">
<bb class='component' />
</view>
</view>
<view class="box-tabbar">
<view class="tab-tiem {{currentTab == idx ? 'active' : 'default' }}" wx:for="{{items}}" wx:key="prototype" wx:for-index="idx" wx:for-item="item" data-current="{{idx}}" bindtap="tabbarClick">
<text class="tab-text" wx:for-index="idx" data-current="{{idx}}" src="{{currentTab == idx ? item.selectedIconPath : item.iconPath }}">{{item.text}}</text>
<image class="iconPath" wx:for-index="idx" data-current="{{idx}}" src="{{currentTab == idx ? item.selectedIconPath : item.iconPath }}"></image>
</view>
</view>
</view>
page.wxss
.iconPath {
width:54rpx;
height: 54rpx;
}
.tab-tiem{
width: 100%;
padding-top: 7rpx;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column-reverse;
background: #e4e4e4;
}
.component{
height: 100%;
}
.root{
height: 100%;
display: flex;
flex-direction: column;
align-items: stretch;
overflow:hidden
}
.box-tabbar {
height: 10%;
width: 100%;
display: flex;
position: fixed;
bottom: 0;
justify-content: space-between;
}
框架結(jié)構(gòu)圖

image.png
注意事項(xiàng):
1.page.wxml使用的是wx:if來控制Component的顯示隱藏,如果使用hidden的話,Component中如果還是用了自定義component的話,自定義component會獲取不到正確的寬高,出現(xiàn)控件無法正常顯示。
2.如果再頁面中使用到自定義Component,用wx:if來控制顯示隱藏的時候,pageLifetimes中的show()函數(shù)不會被調(diào)用,所以邏輯代碼盡量在lifetimes ready()中執(zhí)行。