TabBar是移动应用中常用的一个控件,微信小程序也内置了该控件,使用起来非常简单,定义即可。本文做一个简单的演示。
准备资源
为完成在微信小程序中定义 TabBar, 需要用到一些图片资源。可以在这里下载。
在载以后,将文件解压在小程序项目的根目录中,与 pages 目录平级, 如下所示。
1 2 3 4 5 6
| + assets + images + pages + utils app.js ...
|
添加页面
要使用 TabBar, 首先需要定义每个Tab对应的页面。在样例中,我们定义是个 Tab, 分别是: 主页,分类,购物车和我的。
所以在 app.json 文件中先加入以下是个页面:
1 2 3 4 5 6
| "pages": [ "pages/index/index", "pages/cart/index", "pages/user/index", "pages/classify/index" ],
|
定义 TabBar
在 app.json 中,加入 TabBar 定义,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| "tabBar": { "color": "#999999", "selectedColor": "#479de6", "borderStyle": "white", "backgroundColor": "#fff", "list": [ { "pagePath": "pages/index/index", "iconPath": "assets/images/iconfont-home.png", "selectedIconPath": "assets/images/iconfont-home-active.png", "text": "主页" }, { "pagePath": "pages/classify/index", "iconPath": "assets/images/iconfont-list.png", "selectedIconPath": "assets/images/iconfont-list-active.png", "text": "分类" }, { "pagePath": "pages/cart/index", "iconPath": "assets/images/iconfont-cart.png", "selectedIconPath": "assets/images/iconfont-cart-active.png", "text": "购物车" }, { "pagePath": "pages/user/index", "iconPath": "assets/images/iconfont-user.png", "selectedIconPath": "assets/images/iconfont-user-active.png", "text": "我的" } ] },
|
可以看到,可以通过 tabBar 对象对应的属性定义 TabBar 的外观,包括文字颜色,背景色等等。每一个具体的 Tab 是以数组元素的形式定义在 list 中的。 包括选中该 Tab 后应当显示那个页面,选中的图标等。