微信小程序自定义tabbar

本文详细介绍如何在微信小程序中自定义TabBar,包括创建自定义文件夹、配置app.json、编写JS逻辑与WXML布局,及首页与其他页的onShow方法设置。通过四步骤实现个性化TabBar设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义 tabBar · 小程序

第1步 先在根目录下新建自定义tabBar文件夹(一定要放到根目录下)
在这里插入图片描述

第2步、在 app.json 中的 tabBar 项指定 custom 字段,设置为true,同时其余 tabBar 相关配置也补充完整。

在这里插入图片描述

所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。

在这里插入图片描述

第三步、 修改custom-tab-bar/index.js的文件

Component(
  {
    data :{
    currentIndex: 0,
    color: "#666666",
    selectedColor: "#3d90f7",
      list : [{
        pagePath: "/page/index/index",
        text: "首页",
        iconPath: "/image/home.png",
        selectedIconPath: "/image/home_selected.png"
      },{
        pagePath: "/page/other/index",
        text: "其他",
        iconPath: "/image/my.png",
        selectedIconPath: "/image/my_selected.png"
      }
      ]
    },
    methods:{
      switchTab(e) {
        const url = e.currentTarget.dataset.url;
        const index = e.currentTarget.dataset.index;
        
        wx.switchTab({url: url })
        
        this.setData({
          currentIndex: index
        })
      },
    }
  }
)

custom-tab-bar/index.wxml的文件

<cover-view class="tab-bar">
  <cover-view class="item" bindtap='switchTab' wx:for="{{list}}" wx:key="index" data-index="{{index}}" data-url="{{item.pagePath}}">
    <cover-image class="icon" src="{{index===currentIndex?item.selectedIconPath : item.iconPath}}"></cover-image>
    <cover-view class="{{index===currentIndex?'textselected':'textselected2'}}">{{item.text}}</cover-view>
  </cover-view>
</cover-view>

ps:这里需要注意的是list中的pagePath一定要写绝对路径/pages开头

第四步、把官方给的使用方法放到tabbar跳转页的onShow方法里,selected根据list下标位置进行设置。

首页其他页的js文件添加如下代码:
在这里插入图片描述

onShow: function () {
    // tabbar
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        currentIndex: 0   //和custom-tab-bar/index.js文件的currentIndex是同一个
      })
    }

(用wx.switchTab({url: url })跳转到 【其他页面】 ,相当于刷新custom-tab-bar/index页面,currentIndex数据不会被改变,所以需要在跳转的页面重新设置。 如果是 【自己跳转到自己的页面】 currentIndex数据会发生改变, 所以不加上面那代码,会发现需要点两次数据才会改变------第一次是跳转其他页面,第二次是跳转自己页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值