微信小程序自定義tabBar和遇到的一些問題


第一步

在app.json文件找到“tarBar”對象,然后添加一個屬性,代碼如下:

"tabBar": {
    "custom": true, //添加這個屬性
    "color": "#707070",
    "selectedColor": "#00c4cc",
    "list": [
      {
        "pagePath": "pages/home/index",
        "iconPath": "/static/img/home_def.png",
        "selectedIconPath": "/static/img/home_sel.png",
        "text": "首頁"
      },
      {
        "pagePath": "pages/catetory/index",
        "iconPath": "/static/img/type_def.png",
        "selectedIconPath": "/static/img/type_sel.png",
        "text": "分類"
      },
      {
        "pagePath": "pages/home/index",
        "iconPath": "/static/img/my_def.png",
        "selectedIconPath": "/static/img/my_sel.png",
        "text": "我的"
      }
    ]
  }

 

第二步

在pages文件夾同級目錄下,新建一個文件夾,文件夾名稱為 “custom-tab-bar” ,就跟自定義組件一樣創建,然后自己寫基本樣式,

主要通過fixed定位到底部就行(其實也可以直接去微信公眾平台下載示例代碼):

 

custom-tab-bar組件的基本代碼如下:

index.wxml代碼

<!--miniprogram/custom-tab-bar/index.wxml-->
<cover-view class="tab-bar">
  <cover-view class="tab-bar-border"></cover-view>
  <cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="switchTab">
    <cover-image src="{{selected === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
    <cover-view style="color: {{selected === index ? selectedColor : color}}">{{item.text}}</cover-view>
  </cover-view>
</cover-view>

index.js代碼

Component({
  data: {
    selected: 0,
    color: "#707070",
    selectedColor: "#00c4cc",
    list: [{
      pagePath: "/pages/home/index",
      iconPath: "/static/img/home_def.png",
      selectedIconPath: "/static/img/home_sel.png",
      text: "首頁"
    }, {
        pagePath: "/pages/catetory/index",
        iconPath: "/static/img/type_def.png",
        selectedIconPath: "/static/img/type_sel.png",
      text: "分類"
      }
      // ,{
      //   pagePath: "/pages/home/index",
      //   iconPath: "/static/img/my_def.png",
      //   selectedIconPath: "/static/img/my_sel.png",
      //   text: "我的"
      // }
      ]
  },
  attached() {
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset
      const url = data.path
      wx.switchTab({url})
      console.log(data.index)
      this.setData({
        selected: data.index
      })
    }
  }
})

 

到這里,自定義導航基本能在頁面展示出來了,需要注意的是,每個tab頁面,都要開啟“usingComponents ”項,或者直接在app.json中全局設置

雖然能展示出來了,但你試着切換導航,會發現一個問題,樣式總是對應不上,比如 1  2  3有這三個導航,你點了2之后,選中的樣式是1,點3后,選中的樣式是2,

有點異步的感覺,解決方法是:在每一個tab頁面,在周期函數onShow里添加如下代碼:

if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }

 

注意每個tab頁面的selected值不同,對應“custom-tab-bar”中data的list數組中的下標,this.getTabBar()其實返回的就是自定義的那個導航組件“custom-tab-bar” (可自行打印查看),然后執行setData去修改selected的值,從而讓樣式正常顯示。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM