小程序 cover-view自定義custom-tab-bar及cover-view的坑


小程序的tabBar要做成動態的,所以在app.json配置tabBar的內容就不太能滿足需求了。

1.首先在app.json里把tabBar的"custom"屬性設置為 true;

 

 注意:即使用自定義tabBar,app.json配置tabBar的list屬性也要有內容,list下的屬性也不能為空。否則報錯:

 2.在項目跟目錄添加custom-tab-bar,注意一定要是項目根目錄,新建的是component

好了 上代碼

index.wxss

.tabBar{
  width: 100%;
  height: 50px;
  padding: 4px 0;
  background: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  flex-direction:row;
  justify-content:space-around;
  text-align: center;
  font-size: 13px;
  color: #999;
}
.tabWord{
  padding-top: 6px;
  align-items:center;
}
.image{
  width: 26px;
  height: 26px;
  margin: auto;
}

 index.wxml

<cover-view class="tabBar">
  <cover-view bindtap="switchTab" wx:for="{{list}}" wx:key="index" data-path="{{item.URL}}" data-index="{{index}}">
    <cover-image class="image" src="{{selected === index ? item.SelectedIconPath : item.IconPath}}"/>
    <cover-view class="tabWord" style="color: {{selected === index ? selectedColor : color}}">{{item.MenuTitle}}</cover-view>
  </cover-view>
</cover-view>

 index.js

const app = getApp();
Component({
  /**
   * 組件的屬性列表
   */
  properties: {

  },
  data: {
    selected: 0,
    color: "#333",
    selectedColor: "#63C151",
    list: [
     ]
   },
   lifetimes: {
    //組件的生命周期函數
    attached() {
     let that = this;
     app.watch(that.watchBack,that);
   },
   },
   methods: {
     watchBack(list){
       console.log(list)
      if(list){
         this.setData({
           list
         })
       var page = getCurrentPages().pop();
       if (page) return;
       //如果判斷頁面是否需要刷新 使用路由page.route =="當進入的頁面"
       page.onLoad();
      }
     },
     switchTab(e) {
       const data = e.currentTarget.dataset;
       let url = data.path;
       let menuIndex = data.index;
       wx.switchTab({
         url
       })
       this.setData({
         selected: data.index
       })
     }
   },
  })

在app.js中添加監聽:因為數據是動態的,可能在數據沒加載完之前,自定義tabBar已經加載完成,所以使用個監聽 這個方法可以改成公共的。 目的是獲取到值之后賦值 保證tabbar是有值的。
  watch(method,scope){
    var obj = this.globalData;
    Object.defineProperty(obj,"list", {
      configurable: true,
      enumerable: true,
      set:function (value) {
        this._list = value;
         method.call(scope,value) //使用call改變this指向
      },
      get:function(){
        return this._list
      }
    })
  },
globalData: {
 list:[], //存放tabBar的數據
}

  

關於cover-view:

 

 使用cover-view主要是怕可能用到了原生組件導致原生組件顯示在tabBar上的問題。但是要注意cover-view不建議使用id屬性,最近就不要使用了。有可能找不到相對的元素

並且原生組件不支持層級,所以z-index不生效。


免責聲明!

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



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