小程序模板:专业的小程序模板与静态模板分享平台
小程序
教程
搜索
当前位置 : 首页> 小程序教程> 微信小程序 onTabItemTap:精准监听 TabBar 点击事件

微信小程序 onTabItemTap:精准监听 TabBar 点击事件

1. 配置 TabBar

首先,需要在 app.json 文件中配置 TabBar。示例如下:

{
  "tabBar": {
    "color": "#000000",
    "selectedColor": "#FF0000",
    "backgroundColor": "#FFFFFF",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/images/tabbar/home.png",
        "selectedIconPath": "static/images/tabbar/home-selected.png"
      },
      {
        "pagePath": "pages/mine/mine",
        "text": "我的",
        "iconPath": "static/images/tabbar/mine.png",
        "selectedIconPath": "static/images/tabbar/mine-selected.png"
      }
    ]
  },
  "pages": [
    "pages/index/index",
    "pages/mine/mine"
  ]
}

2. 在页面中使用 onTabItemTap

在每个 TabBar 对应的页面的 js 文件中,可以定义 onTabItemTap 函数来监听点击事件。示例代码如下:

Page({
  onTabItemTap(item) {
    console.log('被点击 TabBar 项的索引:', item.index);
    console.log('被点击 TabBar 项的页面路径:', item.pagePath);
    console.log('被点击 TabBar 项的文字:', item.text);

    // 可以根据不同的索引或页面路径执行不同的操作
    if (item.index === 0) {
      console.log('用户点击了首页');
      // 执行首页相关的操作
    } else if (item.index === 1) {
      console.log('用户点击了我的');
      // 执行我的页面相关的操作
    }
  }
})

注意事项

  • onTabItemTap 只能在 TabBar 对应的页面中使用,其他页面使用该函数无效。

  • 当用户点击当前已选中的 TabBar 项时,onTabItemTap 函数仍然会触发。如果需要避免重复操作,可以在函数中添加相应的判断逻辑。例如:

Page({
  data: {
    currentTabIndex: -1
  },
  onTabItemTap(item) {
    if (item.index === this.data.currentTabIndex) {
      console.log('用户重复点击了当前 TabBar 项');
      return;
    }
    this.setData({
      currentTabIndex: item.index
    });
    // 执行其他操作
  }
})


联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了