微信小程序自定义tabbar页面(引用组件方式)

    技术2026-01-28  7

    最近在做一个小程序,需求是从一个非tabbar页面跳转到tabbar页面,tabbar页面左上角还要有返回键,要返回到原来的非tabbar页面,微信官方的组件不能满足,于是自定义tabbar组件:

    1.tabbar页面 wxml

    <view class='root'> <view class='box-h'> <view wx:if="{{currentTab == 0}}"> <storeworkbench class='storeworkbench' /> </view> <view wx:if="{{currentTab == 1}}"> <storemall 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>

    2.tabbar页面 json

    { "usingComponents": { "storeworkbench": "../storeworkbench/storeworkbench", "storemall": "../storemall/storemall" }, "navigationBarTitleText": "定制店", "navigationBarBackgroundColor": "#4287F8", "navigationBarTextStyle": "white" }

    3.tabbar页面 js

    /** * 页面的初始数据 */ data: { currentTab: 0,//当前选项卡索引 items: [{ "iconPath": "/images/shouye_gongzuotai@2x.png", "selectedIconPath": "/images/home_gztb@2x.png", "text": "工作台" }, { "iconPath": "/images/home_gysc@2x.png", "selectedIconPath": "/images/home_gysc_h@2x.png", "text": "供应商城" } ] }, /** * 选项卡点击事件 */ tabbarClick: function(e) { let that = this; if (this.data.currentTab === e.target.dataset.current) { return false; } else { if(e.target.dataset.current == 1){ wx.setNavigationBarTitle({ title: '供应商城' }) wx.setNavigationBarColor({ backgroundColor: '#ffffff', frontColor: '#000000', }) }else{ wx.setNavigationBarTitle({ title: '工作台' }) wx.setNavigationBarColor({ backgroundColor: '#4287F8', frontColor: '#ffffff', }) } that.setData({ currentTab: e.target.dataset.current, }) } },

    4.tabbar页面 wxss

    page{ margin-top: -2rpx; } .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: #FFFFFF; font-family: MicrosoftYaHei; font-size: 20rpx; color: #C3C6CC; } .storeworkbench{ width: 100%; background-color: red; } .component{ height: 100%; } .root{ width: 100%; height: 100%; display: flex; flex-direction: column; align-items: stretch; overflow:hidden } .box-tabbar { height: 100rpx; width: 100%; display: flex; position: fixed; bottom: 0; justify-content: space-between; box-shadow:0px 2px 4px 2px rgba(66,135,248,0.2); } .active{ font-family: MicrosoftYaHei; font-size: 20rpx; color: #4287F8; } .i_img { width: 100%; height: 1882rpx; }

    在tabbar页面的json中使用usingComponents引用点击对应选项卡的页面,就可以实现自定义tabbar

    Processed: 0.013, SQL: 10