1. 程式人生 > >微信小程式自定義tabbar

微信小程式自定義tabbar

原文地址:http://www.wxapp-union.com/article-1405-1.html
1.建立wxml模板

  1. <template name="tabbar">

  2. <view class="tabbar_box" style="background-color:{{tabbar.backgroundColor}}; border-top-color:{{tabbar.borderStyle}}; {{tabbar.position == 'top' ? 'top:0' : 'bottom:0'}}">

  3. <block wx:for="{{tabbar.list}}" wx:for-item="item" wx:key="index">

  4. <navigator class="tabbar_nav" url="{{item.pagePath}}" style="width:{{1/tabbar.list.length*100}}%; color:{{item.selected ? tabbar.selectedColor : tabbar.color}}" open-type="redirect">

  5. <image class="tabbar_icon" src="{{item.selected ? item.selectedIconPath : item.iconPath}}"></image>

  6. <text>{{item.text}}</text>

  7. </navigator>

  8. </block>

  9. </view>

  10. </template>

2.app.wxss裡定義元件樣式

  1. .tabbar_box{

  2. display: flex;

  3. flex-direction: row;

  4. justify-content: space-around;

  5. position: fixed;

  6. bottom: 0;

  7. left: 0;

  8. z-index: 999;

  9. width: 100%;

  10. height: 120rpx;

  11. border-top: 1rpx solid gray;

  12. }

  13. .tabbar_nav{

  14. display: flex;

  15. flex-direction: column;

  16. justify-content: center;

  17. align-items: center;

  18. font-size: 28rpx;

  19. height: 100%;

  20. }

  21. .tabbar_icon{

  22. width: 61rpx;

  23. height: 61rpx;

  24. }

3.app.js定義全域性函式

  1. editTabBar: function(){

  2. var tabbar = this.globalData.tabbar,

  3. currentPages = getCurrentPages(),

  4. _this = currentPages[currentPages.length - 1],

  5. pagePath = _this.__route__;

  6. (pagePath.indexOf('/') != 0) && (pagePath = '/' + pagePath);

  7. for(var i in tabbar.list){

  8. tabbar.list[i].selected = false;

  9. (tabbar.list[i].pagePath == pagePath) && (tabbar.list[i].selected = true);

  10. }

  11. _this.setData({

  12. tabbar: tabbar

  13. });

  14. },

  15. globalData:{

  16. userInfo:null,

  17. tabbar:{

  18. color: "#000000",

  19. selectedColor: "#0f87ff",

  20. backgroundColor: "#ffffff",

  21. borderStyle: "black",

  22. list: [

  23. {

  24. pagePath: "/pages/tabbar/tabbar",

  25. text: "專案",

  26. iconPath: "/images/item.png",

  27. selectedIconPath: "/images/item_HL.png",

  28. selected: true

  29. },

  30. {

  31. pagePath: "/pages/address/address",

  32. text: "通訊錄",

  33. iconPath: "/images/ts.png",

  34. selectedIconPath: "/images/ts1.png",

  35. selected: false

  36. },

  37. {

  38. pagePath: "/pages/personal/personal",

  39. text: "檔案",

  40. iconPath: "/images/wjj.png",

  41. selectedIconPath: "/images/wjj1.png",

  42. selected: false

  43. }

  44. ],

  45. position: "bottom"

  46. }

  47. }


4.在一級頁面引入模板

  1. <import src="../tabbar/tabbar.wxml"/>

  2. <template is="tabbar" data="{{tabbar}}"/>


5.引入模板的頁面load裡做下處理

  getApp().editTabBar();