小程序使用vantUI自定义tabBar

创建自定义tabBar文件
创建一个与 /pages 的同级目录,命名为 /custom-tab-bar(必须是custom-tab-bar这个名称),注意目录层级与目录命名问题,不可用其他名称命名。在 /custom-tab-bar 下创建四个文件:

index.js
index.json
index.wxml
index.wxss

index.js
在index.js中定义相关数据

  • action : 当前被点击tab的索引
  • list : tab列表

以及一个切换tab时触发的方法:

  • function onChange(event) : 标签切换时触发,修改 active值,点亮被点击的 tab 并进行页面跳转
Component({
  data: {
    // 选中的 tab 
    active: null,
    // 菜单列表
    list: [
      {
        pagePath: '/pages/subscriptions/subscriptions',
        text: '订阅',
        name: 'subscriptions',
        icon: 'bullhorn-o'
      },
      {
        pagePath: '/pages/profile/profile',
        text: '我的',
        name: 'profile',
        icon: 'user-o'
      }
    ]
  },
  methods: {
    // 标签切换
    onChange: function (event) {
      this.setData({ active: event.detail })
      wx.switchTab({
        url: this.data.list[event.detail].pagePath,
      })
    }
  }
})

index.json
在index.js中,将component参数值设置为true,代表这是一个自定义组件:

{
    "compoent": true
}

因为我使用了Vant Weapp的tabBar标签栏,所以还需要引入额外的组件:

{
  "component": true,
  "usingComponents": {
    "van-tabbar": "@vant/weapp/tabbar/index",
    "van-tabbar-item": "@vant/weapp/tabbar-item/index",
    "van-icon": "@vant/weapp/icon/index"
  }
}

ps:这里的路径以实际项目的路径为准
index.wxml
在index.wxml中定义组件形态,我在此使用Vant Weapp的tabBar标签栏,详见代码:

<van-tabbar active="{{ active }}" bind:change="onChange">
  <van-tabbar-item 
  wx:for="{{list}}" 
  wx:key="index"
  icon="{{item.icon}}" 
  data-path="{{item.pagePath}}">
    {{item.text}}
  </van-tabbar-item>
</van-tabbar>

app.json
在app.json中配置参数如下:

  • usingComponents : 仅声明即可
  • tabBar : tabBar组件的具体配置
    • custom : 设为 true ,表示使用自定义组件
    • list : tab 页列表,在列表中的页面将被设置为 tab 页,自动加载 tabBar
{
    "usingComponents":{

    },
    "tabBar":{
        "custom":true,
        "color":"#000000",
        "selectedColor":"#000000",
        "backgroundColor":"#000000",
        "list":[
            {
                "pagePath":"pages/subscriptions/index",
                "text":"订阅",
                "iconPath":"",
                "selectedIconPath":""
            },
            {
                "pagePath":"pages/user/index",
                "text":"关于我",
                "iconPath":"",
                "selectedIconPath":""
            }
        ]
    }
}

实现tabBar选中态
根据微信官方文档描述,每个 tab 页面 tabBar 的实例是不同的:

每个 tab 页下的自定义 tabBar 组件实例是不同的,可通过自定义组件下的 getTabBar 接口,获取当前页面的自定义 tabBar 组件实例。

显而易见,每当切换 tab 页时,我们都需要更新 tabBar 的选中态。关于选中态的实现,官方文档描述如下:

注意:如需实现 tab 选中态,要在当前页面下,通过 getTabBar 接口获取组件实例,并调用 setData 更新选中态。

我们可以在使用到 tabBar 的页面中这样实现:

Page({
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        // 当前页面的 tabBar 索引
        active: 1
      })
    }
  }
})

至此,一个自定义 tabBar 的实现已全部完成。

原文链接:https://cloud.tencent.com/developer/article/1739272

posted @ 2021-03-08 16:39  咚咚呱  阅读(634)  评论(0编辑  收藏  举报