目前開發微信小程序,需求是要在非首頁實現tabbar
的切換效果,但是,官方文檔的tabbar
只能在首頁使用,而且還有個坑,tabbar的第一個頁面必須是app.json
文件pages
數組的第一個,不然顯示不出來。
接下來說一下如何在非首頁實現tabbar
效果,這個效果在Android里面非常的簡單,使用
fragment
進行切換就可以實現,那么也是把這種思維帶到了小程序中,使用component
進行切換,先上代碼。
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": "我的"
}
]
},
/**
* 選項卡點擊事件
*/
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;
}
框架結構圖
image.png
注意事項:
1.page.wxml
使用的是wx:if
來控制Component
的顯示隱藏,如果使用hidden
的話,Component
中如果還是用了自定義component
的話,自定義component
會獲取不到正確的寬高,出現控件無法正常顯示。
2.如果再頁面中使用到自定義Component
,用wx:if
來控制顯示隱藏的時候,pageLifetimes
中的show()
函數不會被調用,所以邏輯代碼盡量在lifetimes
ready()
中執行。