uniapp如何设置tabbar默认选中

在uniapp中,如何设置tabbar的默认选中项?我在pages.json里配置了tabBar,但每次打开小程序都默认选中第一个页面,想要指定其他页面作为默认选中项应该怎么操作?求具体实现方法。

2 回复

pages.json中,找到tabBar配置项,设置selected属性为当前页面的路径即可。例如:

"tabBar": {
  "selected": "/pages/index/index"
}

在 UniApp 中,可以通过 pages.json 文件中的 tabBar 配置项来设置 TabBar 的默认选中项。具体方法如下:

  1. 打开 pages.json 文件:在项目根目录下找到并编辑此文件。
  2. 配置 tabBar:在 tabBar 对象中,使用 selected 属性指定默认选中的 Tab 项索引(从 0 开始计数)。

示例代码:

{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "首页"
      }
    },
    {
      "path": "pages/profile/profile",
      "style": {
        "navigationBarTitleText": "个人中心"
      }
    }
  ],
  "tabBar": {
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/home.png",
        "selectedIconPath": "static/home-active.png"
      },
      {
        "pagePath": "pages/profile/profile",
        "text": "个人中心",
        "iconPath": "static/profile.png",
        "selectedIconPath": "static/profile-active.png"
      }
    ],
    "selected": 0  // 默认选中第一个 Tab(首页)
  }
}

说明

  • selected 的值对应 list 数组中 Tab 项的索引(例如 0 表示第一个 Tab)。
  • 修改后保存文件,重新运行项目即可生效。

如果需要动态切换选中项,可以使用 uni.switchTab API,但默认选中仅在应用启动时由 pages.json 配置决定。

回到顶部