在微信小程序中,可以通过底部选项卡(tabBar)实现不同页面的切换。以下是实现方法:
基本配置方法
-
在 app.json 中配置 tabBar:
{"pages": ["pages/index/index","pages/category/category","pages/cart/cart","pages/user/user"],"tabBar": {"list": [{"pagePath": "pages/index/index","text": "首页","iconPath": "images/tab-home.png","selectedIconPath": "images/tab-home-active.png"},{"pagePath": "pages/category/category","text": "分类","iconPath": "images/tab-cate.png","selectedIconPath": "images/tab-cate-active.png"},{"pagePath": "pages/cart/cart","text": "购物车","iconPath": "images/tab-cart.png","selectedIconPath": "images/tab-cart-active.png"},{"pagePath": "pages/user/user","text": "我的","iconPath": "images/tab-user.png","selectedIconPath": "images/tab-user-active.png"}],"color": "#999","selectedColor": "#ff2d4a","backgroundColor": "#fafafa"}
}
关键配置项说明
-
pagePath
: 页面路径,必须在pages
数组中已经定义 -
text
: tab 上显示的文字 -
iconPath
: 未选中时的图标路径 -
selectedIconPath
: 选中时的图标路径 -
color
: tab 文字默认颜色 -
selectedColor
: tab 文字选中时的颜色 -
backgroundColor
: tab 背景色
注意事项
-
tabBar 最少配置2个,最多5个 tab
-
tabBar 的页面第一次打开时不会触发 onLoad,只有在切换时才会触发
-
可以通过
wx.switchTab
API 进行页面跳转
自定义 tabBar
如果需要更复杂的效果,可以使用自定义 tabBar:
-
在 app.json 中设置
"custom": true
-
创建 custom-tab-bar 组件
-
在各页面中使用这个自定义组件
{"tabBar": {"custom": true,"list": [{"pagePath": "pages/index/index","text": "首页"}]}
}
这样你就可以完全控制 tabBar 的外观和行为了。