微信小程序 Tab组件
时间: 2025-04-22 21:24:44 浏览: 19
### 微信小程序 Tab 组件使用教程
#### 一、TabBar 基本配置
在微信小程序中,`tabBar` 是用于实现底部导航栏的功能。此功能允许开发者通过简单的 JSON 配置来创建固定的标签页效果[^1]。
```json
{
"tabBar": {
"list": [
{
"pagePath": "pages/index/index",
"text": "首页"
},
{
"pagePath": "pages/logs/logs",
"text": "日志"
}
]
}
}
```
上述代码展示了如何定义两个基本的 tabBar 项:“首页”和“日志”。每个对象都应包含 `pagePath`(指向页面路径) 和 `text`(显示的文字)。
#### 二、动态修改 TabBar
对于更复杂的交互需求,比如更新徽章数或切换选中的 tab,可以调用相应的 API 方法:
- 设置 badge 文字:`wx.setTabBarItem({index, text})`
- 显示/隐藏红点提示:`wx.showTabBarRedDot()/ wx.hideTabBarRedDot()`
- 切换到指定的 tabBar 页面:`wx.switchTab()`
这些方法提供了灵活的操作选项,使得应用程序可以根据用户的操作即时调整界面状态。
#### 三、完整示例
下面是一个完整的例子,它不仅设置了静态的 tabBar 结构,还包含了通过 JavaScript 动态改变 tabBar 的逻辑。
##### app.json 中的 tabBar 定义:
```json
{
"tabBar": {
"color": "#000",
"selectedColor": "#ff8c00",
"borderStyle": "black",
"backgroundColor": "#fff",
"list": [{
"pagePath": "pages/home/home",
"text": "Home",
"iconPath": "./assets/images/home.png",
"selectedIconPath": "./assets/images/home-active.png"
}, {
"pagePath": "pages/cart/cart",
"text": "Cart",
"badge": "99+",
"iconPath": "./assets/images/cart.png",
"selectedIconPath": "./assets/images/cart-active.png"
}]
}
}
```
##### 在某个 .js 文件里动态更改 tabBar:
```javascript
Page({
onLoad: function () {
// 更新 Cart 的 Badge 数量
wx.setTabBarItem({
index: 1,
text: '购物车 (2)',
success(res) { console.log('success', res); }
});
// 添加红点提醒至 Home
wx.showTabBarRedDot({ index: 0 })
},
onShow:function(){
// 当前页面显示时触发
}
})
```
阅读全文
相关推荐


















