小程序自定义导航栏组件

创建导航栏组件

导航栏wxml:

<view class="nav-content">     <view class='nav-wrap' style='height:{{height}}px;'>         <view class="navbar-content">             <!--返回按钮-->             <view class="back" bindtap="_navback" wx:if="{{!navbackHidden}}">                 <image class="img" src='../../images/backImage.png'/>             </view>             <!--标题-->             <text class='nav-title' wx:if="{{title.length>0}}">{{title}}             </text>             <slot name="before"></slot>             <view class="back"></view>         </view>     </view>     <view style="background:white;width:100%">         <slot name="after"></slot>     </view> </view> <view style='height:{{height}}px;width:100%;'/> <view style='height:{{slotHeight}}rpx;width:100%;'/>

导航栏wxss

.nav-content {   position: fixed;   display: flex;   flex-direction: column;   justify-content: flex-start;   align-items: center;   width: 100%;   z-index: 99999;   top: 0; } .nav-wrap {   display: flex;   flex-direction: column;   justify-content: flex-end;   align-items: center;   width: 100%;   background-color: #9aafc8;   border-bottom: 1rpx solid #f0f0f0; } .navbar-content {   display: flex;   flex-direction: row;   justify-content: space-between;   align-items: center;   width: 100%;   height: 44px; } /* 标题要居中 */ .nav-title {   text-overflow: ellipsis;   white-space: nowrap;   color: black;   float: left;   width: 500rpx;   font-size: 15px;   text-align: center; } .back {   display: flex;   flex-direction: row;   justify-content: center;   align-items: center;   width: 30px;   height: 30px; } .back .img {   width: 9px;   height: 16px; }

导航栏JS

Component({   options: {     multipleSlots: true // 在组件定义时的选项中启用多slot支持   },   /**    * 组件的属性列表    */   properties: {     // 标题     title: String,     // 是否隐藏返回按钮     navbackHidden: {       type: Boolean,       value: false     },     // 底部模板高度     slotHeight: {       type: Number,       value: 0,     }   },    /**    * 组件的初始数据    */   data: {     height: '',   },   /**    * 定义导航栏的高度    */   attached: function () {     const app = getApp()     this.setData({       height: app.globalData.navHeight,     })   },   /**    * 组件的方法列表    */   methods: {     // 返回上一页面     _navback() {       wx.navigateBack()     }   } })

在页面中使用导航栏组件

页面json

{   "usingComponents": {     "custom-navbar": "../../components/customnavbar"   },   "navigationStyle": "custom" }

页面wxml

<view class="page">   <custom-navbar title="{{title}}">     <view slot="before" class="tab-button-content">       <view class="{{tabIndex == index?'tabbtn-sel':'tabbtn-unsel'}}" data-idx="{{index}}"         wx:for="{{['粉丝', '关注']}}" wx:key="index" bindtap="tabButtonClick">{{item}}</view>     </view>   </custom-navbar>   <view class="page__hd">   </view>   <view class="page__bd">   </view> </view>