1. 程式人生 > 程式設計 >微信小程式自定義tabbar元件

微信小程式自定義tabbar元件

本文例項為大家分享了微信小程式自定義tabbar元件的具體程式碼,供大家參考,具體內容如下

由於專案需求,必須自己寫元件:

第一步:在App.json中配置tabBar,自定也元件也必須配置,"custom":true,list裡配置所有的tabbar頁面。

 "tabBar": {
 "custom": true,"color": "red","selectedColor": "#3b81d7","backgroundColor": "#000000","list": [{
 "pagePath": "pages/Role/InsureIndex/index","text": "首頁"
 },{
 "pagePath": "pages/Role/MineIndex/index",{
 "pagePath": "pages/index/userInfo/userInfo","text": "我的"
 }]
 },

第二步:在pages的同級目錄新建元件,資料夾名字:custom-tab-bar,自定義元件檔名為index。元件程式碼如下,應該都能看懂。

index.js

Component({
 properties: {},data: {
 indexImg: "../static/images/tabBar/[email protected]",indexSelectImg: "../static/images/tabBar/[email protected]",aboutUsImg: "../static/images/tabBar/tab_ihttp://www.cppcns.com[email protected]",aboutUsSelectImg: "../static/images/tabBar/[email protected]",_tabbat: null,iPhoneX: false,urls: ['/pages/Role/InsureIndex/index','/pages/index/userInfo/userInfo'
 ]
 },attached() {
 var self = this
//此為業務程式碼,可不看
 wx.getStorage({
 key: 'userInfo',success: function (res) {
 const {
  userRoleCode
 } = res.data
 if (userRoleCode == '50' || userRoleCode == '70') {
  self.setData({
  ["urls[0]"]: '/pages/Role/MineIndex/index'
  })
 } else if (userRoleCode == '30' || userRoleCode == '35' || userRoleCode == '40') {
  self.setData({
  ["urls[0]"]: '/pages/Role/InsureIndex/in
程式設計客棧
dex' }) } } }) wx.getSystemInfo({ success(res) { console.log(res.model) if (res.model.indexOf('iPhone X') >= 0) { self.setData({ iPhoneX: true }) } } }) },/** * 元件的方法列表 */ methods: { switchTap: function (e) { var self = this var index = e.currentTarget.dataset.index; var urls = self.data.urls wx.switchTab({ url: urls[index],}) } } })

index.wxml

<div class="_tabbar {{iPhoneX?'_iPhoneX':''}}">
 <div class="titem {{_tabbat==0?'tCdk':''}}" data-index="0" bind:tap="switchTap">
 <image src="{{_ta程式設計客棧bbat==0?indexSelectImg:indexImg}}" />
 首頁
 </div>
 <div class="titem {{_tabbat==1?'tCdk':''}}程式設計客棧" data-index="1" bind:tap="switchTap">
 <image src="{{_tabbat==1?aboutUsSelectImg:aboutUsImg}}" />
 我的
 </div>
</div>

index.wxss

._tabbar {
 width: 100%;
 height: 120rpx;
 display: flex;
 align-items: center;
 background: #fff;
 font-size: 26rpx;
 color: #999999;
 box-shadow: 0px -7rpx 13rpx 0px rgba(193,185,204,0.13);
}
 
程式設計客棧._tabbar .titem {
 text-align: center;
 width: 50%;
}
 
._tabbar .titem image {
 display: block;
 margin: auto;
 width: 48rpx;
 height: 48rpx;
 margin-bottom: 10rpx;
}
 
._tabbar .tCdk {
 color: #37ADFE;
}
 
._iPhoneX {
 height: 148rpx;
}

index.json

{
 "component": true,"usingComponents": {}
}

以上為元件程式碼,點選tabbar跳轉頁面時,會重新載入tabbar元件,導致選中樣式一直是預設的,因此需要在用到tabbar的頁面的js檔案中做如下操作:(以 “首頁”頁面為例)

onShow: function () {
 this.getTabBar().setData({
 _tabbat: 0
 })
 },

以上就已經完成了,但是看網上大家說會出現兩個tabBar,我這邊是沒出現(一個自定義,一個自帶的),如果出現的話,在app.js中的onLaunch函式中加入 wx.hideTabBar() , 隱藏自帶的tabbar就可以了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。