小程序自定义头部组件

1.新建文件navbar

在这里插入图片描述

2.index.wxml

<cover-view class="nav-wrap" style='height: {{height*2 + 25}}px;' >
    <!-- 导航栏 中间的标题 -->
  <cover-view class='nav-title' style='line-height: {{height*2 + 45}}px;'>
      {{navbarData.name}}
  </cover-view>

  <cover-view style='display: flex; justify-content: space-around;flex-direction: column;'>
   <!-- 导航栏  左上角的返回按钮 -->
    <cover-view class='nav-capsule' style='height: {{height*2 + 45}}px;'>
      <cover-view bindtap='_navback'>
        <cover-image src='图片返回按钮地址' mode='aspectFill' class='back-pre' ></cover-image>
      </cover-view>
    </cover-view>
  </cover-view>

</cover-view>

在这里插入图片描述

wxss

/* 顶部要固定定位   标题要居中   自定义按钮和标题要和右边微信原生的胶囊上下对齐 */
.nav-wrap {
  position: fixed;
  width: 100%;
  top: 0;
  background: #fff;
  color: #000;
  z-index: 9999999;
  /* background: transparent */
}
/* 标题要居中 */
.nav-title {
  position: absolute;
  text-align: center;
  max-width: 330rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  font-size: 36rpx;
  color: #2c2b2b;
  font-weight: 600;
}
.nav-capsule {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}
.back-pre {
  width: 52rpx;
  height: 52rpx;
  margin-top: 4rpx;
  padding: 10rpx;
}
.nav-capsule {
   display: flex;
  align-items: center;
  margin-left: 30rpx;
  width: 140rpx;
  justify-content: space-between;
  height: 100%;
}


js

const app = getApp()
Component({
  properties: {
    navbarData: {   //navbarData   由父页面传递的数据
      type: Object,
      value: {},
      height: app.globalData.height
    }
  },
  data: {
    height: '',
    //默认值  默认显示左上角
    navbarData: {
    }
  },
  attached: function () {
    // 定义导航栏的高度   方便对齐
    this.setData({
      height: app.globalData.height
    })
  },
  created() {
    this.setData({
      height: app.globalData.height
    })
  },
  methods: {
    // 返回上一页面
    _navback() {
      wx.navigateBack()
    }
  }
}) 

3.使用

1.app.json添加

	"navigationStyle": "custom"

在这里插入图片描述
2.app.js 获取不同设备的高度

App({
  onLaunch: function () {
    //获取设备顶部窗口的高度(不同设备窗口高度不一样,根据这个来设置自定义导航栏的高度
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.height = res.statusBarHeight
      }
    })
  },
  globalData:{
    height: 0
  }
})

3.在页面中使用组件
*页面json引入组件

{
  "usingComponents": {
    "nav-bar" : "../index/index"
  }
}

*页面使用

<nav-bar navbar-data='{{navbarData}}' ></nav-bar>
<view style="padding-top:{{height}}px">
		....内容
</view>

*页面js

Page({
  data: {
  	height: app.globalData.height * 2 + 25,
    navbarData:{
      name: '我是标题'
    }
  },
  onLoad: function (options) {

  },
})

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值