小程序自定义tabbar组件

开发时选择vant Weapp作为UI库,其中使用了vant的tabbar来代替小程序原有的tabbar。
本来想用vant tabbar和小程序的自定义tabbar结合来做,具体可以参考:
小程序自定义tabbar

但是在实际使用中,在引用tabbar组件的页面,this.getTabBar总是取不到值,一直null,大概是因为组件中的list和app.json的list页面不一致,我的组件List路径多一个"/",可是改成一模一样的路径,跳转时就会出错。

onShow: function () {  
    console.log(this.getTabBar())  
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0,        
      })
    }
  },

算了算了,就不用小程序自带的自定义tabbar,直接写一个新的,反而更方便,利用组件的properties来设置tabbar的selected。

// tabbar.wxml

<van-tabbar active="{{ selected }}" bind:change="onChange">
  <van-tabbar-item wx:for="{{list}}" wx:key="index" icon="{{item.icon}}" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab" class="">
    {{item.text}}
  </van-tabbar-item>
</van-tabbar>
// tabbar.js
Component({
  properties: {
    selected: Number
  },
  data: {   
    color: "#7A7E83",
    selectedColor: "#3cc51f",
    list: [{
      pagePath: "/pages/todos/todos",
      icon: "notes-o",
      text: "todo"
    }, {
      pagePath: "/pages/bookView/bookView",
      icon: "description",
      text: "book"
    }]
  },
  attached() {},
  methods: {
    onLoad: function () {
      this.data.selected = 0
    },
    switchTab(e) {      
      const data = e.currentTarget.dataset
      this.setData({
        selected: data.index
      })
      const url = data.path
      wx.navigateTo({ url});
    }
  }
})
// 在页面中引用
// page.js
{
  "usingComponents": {    
    "tab-bar": "../../components/custom-tab-bar/index"
  }
}

// page.wxml
<tab-bar selected="1" />

直接写死了selected,很方便,自己用用足够。当然也可以根据当前页面来判断selected的值,这个需要自己加一些代码。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

immocha

人生得意须尽欢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值