uni-app上自定义微信小程序的tabbar

缪远航
2023-12-01

今天用uni-app开发微信小程序时,修改tabbar的样式无效,如selectedColor, iconWidth等,明明官网上都有这些属性,但在模拟器上就是没有效果。

自定义tabbar

1、在微信官网,自定义tabbar的页面,下载自定义tabbar示例代码;将其中的custom-tab-bar目录整个拷贝到项目根目录下;

2、修改custom-tab-bar/index.js的文件,路径都改为自己uni-app项目下的页面路径和图片路径

Component({
  data: {
    selected: 0,
    color: "rgba(0,0,0,0.39)",
    selectedColor: "rgba(0,0,0,0.93)",
    list: [{
				"pagePath": "/pages/index/index",
				"iconPath": "/static/icon/11.png",
				"selectedIconPath": "/static/icon/c11.png",
				"text": "首页"
			},
			{
				"pagePath": "/pages/goods/index2",
				"text": "商品",
				"iconPath": "/static/icon/22.png",
				"selectedIconPath": "/static/icon/c22.png"
			},
			{
				"pagePath": "/pages/shop/home",
				"text": "门店",
				"iconPath": "/static/icon/33.png",
				"selectedIconPath": "/static/icon/c33.png"
			},
			{
				"pagePath": "/pages/my/index",
				"text": "我的",
				"iconPath": "/static/icon/44.png",
				"selectedIconPath": "/static/icon/c44.png"
			}
		]
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      this.setData({
        selected: data.index
      })
    }
  }
})

3、pages.json文件tabbar配置:设置"custom": true

"tabBar": {
		"custom":true,
		"selectedColor": "rgba(0,0,0,0.93)",
		"color": "rgba(0,0,0,0.39)",
		"spacing": "4px",
		"iconWidth": "24px",
		"fontSize": "10px",
		"height": "49px",
		"list": [{
				"pagePath": "pages/index/index",
				"iconPath": "static/icon/11.png",
				"selectedIconPath": "static/icon/c11.png",
				"text": "首页"
			},
			{
				"pagePath": "pages/goods/index2",
				"text": "商品",
				"iconPath": "static/icon/22.png",
				"selectedIconPath": "static/icon/c22.png"
			},
			{
				"pagePath": "pages/shop/home",
				"text": "门店",
				"iconPath": "static/icon/33.png",
				"selectedIconPath": "static/icon/c33.png"
			},
			{
				"pagePath": "pages/my/index",
				"text": "我的",
				"iconPath": "static/icon/44.png",
				"selectedIconPath": "static/icon/c44.png"
			}
		]
	}

4、在main.js加入

// #ifdef MP-WEIXIN
Vue.mixin({
    methods:{
        setTabBarIndex(index) {
            if (typeof this.$mp.page.getTabBar === 'function' &&
            this.$mp.page.getTabBar()) {
                this.$mp.page.getTabBar().setData({
                    selected: index
                })
            }
        }
    }
})
// #endif

5、在各个tabbar页面中调用setTabBarIndex方法,例如:

首页pages/index/index中加入

onShow(e) {
	// #ifdef MP-WEIXIN
	this.setTabBarIndex(0);
	// #endif
},

然后在custom-tab-bar中修改相应的样式即可。

 类似资料: