在微信小程序中實現自定義 tabBar
可以為你的應用提供更加靈活和個性化的底部導航菜單。由于微信小程序的官方 tabBar
配置功能有限,自定義 tabBar
成為了很多開發者實現復雜底部導航的選擇。以下是一個簡單的示例,說明如何在小程序中實現自定義 tabBar
。
步驟 1: 配置 app.json
首先,你需要在 app.json
中配置 tabBar
的基礎信息,但 custom
字段需要設置為 true
來啟用自定義 tabBar
。
{"pages": ["pages/index/index","pages/logs/logs","pages/profile/profile"],"window": {"backgroundTextStyle": "light","navigationBarBackgroundColor": "#fff","navigationBarTitleText": "WeChat","navigationBarTextStyle": "black"},"tabBar": {"list": [{"pagePath": "pages/index/index","text": "首頁"},{"pagePath": "pages/logs/logs","text": "日志"},{"pagePath": "pages/profile/profile","text": "我的"}],"custom": true,"color": "#7A7E83","selectedColor": "#3cc51f","borderStyle": "black"}
}
步驟 2: 創建自定義 tabBar 組件
在項目的根目錄下創建一個名為 custom-tab-bar
的文件夾,并在其中創建所需的文件(如 index.js
、index.json
、index.wxml
、index.wxss
)。
index.js
這里可以處理邏輯,比如根據當前頁面切換 tab。
Component({data: {selected: 0,list: [{pagePath: '/pages/index/index',text: '首頁'}, {pagePath: '/pages/logs/logs',text: '日志'}, {pagePath: '/pages/profile/profile',text: '我的'}]},methods: {switchTab: function(e) {const data = e.currentTarget.dataset;if (this.data.selected === data.index) return;wx.switchTab({url: data.path});},onShow: function(e) {// 當 tabBar 顯示時觸發,可以根據需要獲取當前頁面路徑const { path } = getCurrentPages().pop();this.setData({selected: this.data.list.findIndex(tab => tab.pagePath === path)});}}
});
index.json
定義組件的配置信息。
{"usingComponents": {}
}
index.wxml
定義 tabBar 的結構。
<view class="tab-bar"><block wx:for="{{list}}" wx:key="index" wx:for-index="idx"><view class="tab-item {{selected === idx ? 'active' : ''}}" data-path="{{item.pagePath}}" data-index="{{idx}}" bindtap="switchTab">{{item.text}}</view></block>
</view>
index.wxss
添加樣式。
.tab-bar {display: flex;justify-content: space-around;background-color: #fff;position: fixed;bottom: 0;left: 0;right: 0;height: 50px;
}.tab-item {padding: 10px 0;text-align: center;
}.tab-item.active {color: #3cc51f;
}
步驟 3: 在 app.js 中使用自定義 tabBar
在 app.js
中引入并使用自定義的 tabBar 組件。
App({onLaunch: function () {// 在這里可以執行一些啟動時的邏輯},usingComponents: {'不同角色,控制查看底部菜單權限實現效果1:實體店
實現效果2:回收公司
