小程序自定义底部导航 custom-tab-bar
1. app.json
2. 将 custom-tab-bar 放到根目录下(pages同级)
3. custom-tab-bar 代码
{ "component": true } Component({ data: { USERTYPE:'customer', selected: 0, color: "#7A7E83", selectedColor: "#3cc51f", listAll: [{ type:'customer', pagePath: "/pages/c_home/index", iconPath: "/images/tabbar/home.png", selectedIconPath: "/images/tabbar/home-a.png", text: "首页" }, { type:'customer', pagePath: "/pages/c_mine/index", iconPath: "/images/tabbar/mine.png", selectedIconPath: "/images/tabbar/mine-a.png", text: "我的" }, { type:'business', pagePath: "/pages/b_home/index", iconPath: "/images/tabbar/b_home.png", selectedIconPath: "/images/tabbar/b_home-a.png", text: "主页" }, { type:'business', pagePath: "/pages/b_mine/index", iconPath: "/images/tabbar/b_mine.png", selectedIconPath: "/images/tabbar/b_mine-a.png", text: "我的" }], list:[], }, observers:{ 'USERTYPE': function(newVal, oldVal){ //监听systemId的数据变化 let listAll = this.data.listAll let list = [] if (newVal === 'business') { list = listAll.slice(2,4) } else { list = listAll.slice(0,2) } this.setData({ list }) } }, methods: { switchTab(e) { const data = e.currentTarget.dataset const url = data.path wx.switchTab({url}) } } }) <view class="tab-bar"> <view class="tab-bar-border"></view> <view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab"> <image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></image> <view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</view> </view> </view> .tab-bar { position: fixed; bottom: 0; left: 0; right: 0; height: 96rpx; background: white; display: flex; padding-bottom: env(safe-area-inset-bottom); } .tab-bar-border { background-color: rgba(250,250,250 0.33); position: absolute; left: 0; top: 0; width: 100%; height: 1px; transform: scaleY(0.5); } .tab-bar-item { flex: 1; text-align: center; display: flex; justify-content: center; align-items: center; flex-direction: column; } .tab-bar-item image { width: 27px; height: 27px; } .tab-bar-item view { font-size: 10px; }
4. 登录成功本地存用户类型
wx.setStorageSync('USERTYPE', 'business') or
wx.setStorageSync('USERTYPE', 'customer')
5.tabbar 页面 onShow
if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 0, USERTYPE:wx.getStorageSync('USERTYPE') }) }
6.注意 custom-tab-bar js 代码 custom-tab-bar USERTYPE 要用
observers 否则页面跳转会混乱(踩过坑),之前那块的逻辑写到了 created 里面