來自:https://blog.csdn.net/qq_43379916/article/details/120206962
1. app.json
// 需要先定義tabBar頁面 // “pages” 配置里面也不要忘了 "tabBar": { "custom": true, "list": [ { "pagePath": "pages/index/index" }, { "pagePath": "pages/goods/index" } ] }
2. app.js
// app.js App({ //定義全局setTabbar方法 $setTabbar(that,currentName){ if(typeof that.getTabBar == 'function' && that.getTabBar()){ let tabbar = that.getTabBar(); console.log(tabbar); tabbar.setData({ currentName }) } } })
3. index.wxml,goods.wxmll
Page({ /** * 頁面的初始數據 */ data: { }, onShow(){ /* 返回當前頁面的 custom-tab-bar 的組件實例,詳見【自定義 tabBar】 注意:自定義tabbar的名稱必須為:custom-tab-bar,而且路徑必須在根目錄下 不然getTabBar方法找不到 */ getApp().$setTabbar(this,'index'); //'index' 根據頁面來 在下面的tabbarList的name屬性需要用到 } })
4. custom-tab-bar 組件必須在根目錄,custom-tab-bar/index.wxml
5. custom-tab-bar/index.js
// ps:資源就自定義了哈 //聲明這是一個組件 Component({ data:{ //組件私有數據 currentName:'index', //准備好自定義tabbar資源 //自定義的tabBar 需要在app.json配置中存在 tabbarList:[{ "pagePath": "/pages/index/index", //使用switchTab跳轉時需要在page前面加上 / 斜杠 "text": "index", "iconPath": "../assets/tabbar/1-1.png", "selectedIconPath": "../assets/tabbar/1.png", "style":'', "name":'index' }, { "pagePath": "/pages/goods/index", "text": "goods", "iconPath": "../assets/tabbar/2-2.png", "selectedIconPath": "../assets/tabbar/2.png", "style":'', "name":'goods' }] }, lifetimes:{ //組件生命周期 attached(){ //在組件實列進入頁面節點樹時執行 console.log('嘿,我被執行了'); } }, methods:{ //組件定義的方法(濃濃的既視感) swicthTabbar(e){ let { index} = e.currentTarget.dataset; wx.switchTab({ url: this.data.tabbarList[index].pagePath, }) } } })
6. custom-tab-bar/index.wxml
<!-- 自定義tabbar文檔介紹:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/custom-tabbar.html --> <!-- cover-view 是為了防止層級問題,目前原生組件均已支持同層渲染,使用view也是可以的 --> <!-- ps:文檔里面說使用 cover-view,那就用這個實現一下 --> <!-- 會默認出現到最底部,覆蓋在原生組件之上的文本視圖 --> <cover-view class="custom-tabbar"> <cover-view wx:for="{{tabbarList}}" wx:key="index" class="tabbar-item" data-index="{{index}}" bindtap="swicthTabbar"> <cover-image src="{{currentName == item.name ? item.selectedIconPath : item.iconPath}}" class="tabbar-icon" style="{{item.style}}"></cover-image> <cover-view class="{{currentName == item.name ? 'text-active' : 'tabbar-text'}}">{{item.text}}</cover-view> </cover-view> </cover-view>
7. custom-tab-bar/index.wxss
.custom-tabbar{ position: fixed; bottom: 0; left: 0; right: 0; background-color: #fff; box-shadow: 0px 0px 4rpx rgba(0, 0, 0, 0.3); height: 96rpx; /*(兼容有安全區域的手機)*/ padding-bottom: constant(safe-area-inset-bottom);/*兼容 IOS<11.2*/ padding-bottom: env(safe-area-inset-bottom);/*兼容 IOS>11.2*/ display: flex; } .tabbar-item{ display: flex; justify-content:center; align-items: center; flex: 1; flex-direction: column; font-size: 24rpx; } .tabbar-icon{ width: 44rpx; height: 44rpx; } .tabbar-text{ color: #9c9c9c; } .text-active{ color: #000; }