小程序vant-tabbar使用示例,及报错处理
- 1. 配置信息
- 2. 添加 tabBar 代码文件
- 3. 编写 tabBar 代码
- `custom-tab-bar/index.ts`
- `custom-tab-bar/index.json`
- `custom-tab-bar/index.wxml`
使小程序使用vant-tabbar组件时,遇到以下报错:Couldn’t found the ‘custom-tab-bar/index.json’ file relative to ‘app.json.json’
vant-tabbar是自定义tabBar,所以需要遵循以下规则
自定义 tabBar
基础库 2.5.0 开始支持,低版本需做兼容处理。
在自定义 tabBar 模式下
- 为了保证低版本兼容以及区分哪些页面是 tab 页,tabBar 的相关配置项需完整声明,但这些字段不会作用于自定义 tabBar 的渲染。
- 此时需要开发者提供一个自定义组件来渲染 tabBar,所有 tabBar 的样式都由该自定义组件渲染。推荐用 fixed 在底部的 cover-view + cover-image 组件渲染样式,以保证 tabBar 层级相对较高。
- 与 tabBar 样式相关的接口,如 wx.setTabBarItem 等将失效。
- 每个 tab 页下的自定义 tabBar 组件实例是不同的,可通过自定义组件下的 getTabBar 接口,获取当前页面的自定义 tabBar 组件实例。
- 注意:如需实现 tab 选中态,要在当前页面下,通过 getTabBar 接口获取组件实例,并调用 setData 更新选中态。可参考底部的代码示例。
使用流程
1. 配置信息
- 在 app.json 中的 tabBar 项指定 custom 字段,同时其余 tabBar 相关配置也补充完整。
- 所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。
示例
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [
{
"pagePath": "pages/index/index"
},
{
"pagePath": "pages/user/user"
}
]
},
"pages": [
"pages/index/index",
"pages/user/user",
"custom-tab-bar/index"
],
}
2. 添加 tabBar 代码文件
在代码根目录下添加入口文件,务必注意,目录不能有错,tabbar目录下命名必须是index,跟pages是同级的,不然会报以下错误:Couldn’t found the ‘custom-tab-bar/index.json’ file relative to ‘app.json.json’
custom-tab-bar/index.ts
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.less
3. 编写 tabBar 代码
custom-tab-bar/index.ts
Page({
/**
* 页面的初始数据
*/
data: {
active: 0,
list: [
{
icon: 'home-o',
text: '概况',
url: '/pages/index/index'
},
{
icon: 'user-o',
text: '个人信息',
url: '/pages/user/user'
}
]
},
onLoad() {
const page:any = getCurrentPages().pop();
console.log(page);
this.setData({
active: this.data.list.findIndex(item => item.url === `/${page.route}`)
});
},
/**
* tab点击事件
* @param event
*/
tabOnChange(event: any) {
this.setData({ active: event.detail });
wx.switchTab({
url: this.data.list[event.detail].url
})
},
})
custom-tab-bar/index.json
{
"component": true,
"usingComponents": {
"van-tabbar": "@vant/weapp/tabbar/index",
"van-tabbar-item": "@vant/weapp/tabbar-item/index"
}
}
custom-tab-bar/index.wxml
<van-tabbar active="{{ active }}" bind:change="tabOnChange">
<van-tabbar-item wx:for="{{ list }}" wx:key="index" icon="{{ item.icon }}">{{
item.text
}}</van-tabbar-item>
</van-tabbar>