微信小程序自定义tabbar

官方文档给了自定义tabbar 的方法 ,用下来感觉还是不错的。

1. 配置信息

在 app.json 中的 tabBar开启custom 字段。
所有 tab 页的 json 里需声明 usingComponents 项,也可以在 app.json 全局开启。

{
  "tabBar": {
    "custom": true,   // 表示使用自定义 tabbar 
    "color": "#000000",  // 可以不填 , 兼容低版本
    "selectedColor": "#000000",  // 可以不填 , 兼容低版本
    "backgroundColor": "#000000",  // 可以不填 , 兼容低版本
    // 以下必填
    "list": [{
      "pagePath": "pages/index/index",
      "text": "首页"
    }, {
      "pagePath": "pages/user/user",
      "text": "我的"
    }]
  },
}
2. 添加 tabBar 代码文件

在根目录下增加文件(必须一模一样)

3.编写custom-tab-bar文件

index.wxml

<cover-view wx:if="{{showBar==true}}" class="tab-bar" bindtap="tabChange">
  <cover-view data-url="/pages/index" class="tab-item {{tabIndex == 1? 'active' :''}}">首页</cover-view>
  <cover-view data-url="/pages/login" class="tab-item {{tabIndex == 2? 'active' :''}}">我的</cover-view>
</cover-view>

index.js

const app = getApp()
Component({
  properties: {
    tabIndex:{  // 接收页面传入的数据
      type:String,
      value:'1'
    }
  },
  data: {
    showBar:true,
    mainColorNumber: wx.getStorageSync('mainColorNumber')
  },
  // 组件生命周期
  lifetimes: {
    attached () {

    },
    detached () {

    }
  },
  // 兼容v2.2.3以下写法
  attached () {

  },
  // 挂载页面的生命周期
  pageLifetimes: {

  },
  methods: {
    tabChange(e) {
      const url = e.target.dataset.url
      wx.switchTab({
        url
      })
      this.setData({
        mainColorNumber: wx.getStorageSync('mainColorNumber')
      })
    }
  }
})

 index.js

{
  "component": true
}

index.wxss

.tab-bar{
  width: 100%;
  height: 120rpx;
  background-color: #FFFFFF;
  color: #10272A;
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 0 5px #e7e7e7;
}

.tab-item{
  line-height: 50px;
  text-align: center;
  width: 50%;
  font-size: 16px;
  font-weight: 600;
}

 

4.getTabbar的应用

在每个有tabbar的页面的js文件中增加

 onShow(){
    this.getTabBar().setData({
      tabIndex: 2,
    })
  }

我index.js文件中使用到的showBar的值也可以在别的页面随时改变,也是使用getTabBar

this.getTabBar().setData({
  showBar: true
})

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值